From 544928b8a5c438b024aff7dca7e31061dce55c41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Fri, 8 Sep 2023 15:27:12 +0300 Subject: [PATCH 1/2] refactor(timestamp): remove redundant `.UTC()` call Unix timestamps are always from UTC epoch, and calculation from given `time.Time` is independent of its location. --- ulid.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ulid.go b/ulid.go index 2064dd4..5a6d30b 100644 --- a/ulid.go +++ b/ulid.go @@ -427,8 +427,8 @@ func MaxTime() uint64 { return maxTime } // Now is a convenience function that returns the current // UTC time in Unix milliseconds. Equivalent to: // -// Timestamp(time.Now().UTC()) -func Now() uint64 { return Timestamp(time.Now().UTC()) } +// Timestamp(time.Now()) +func Now() uint64 { return Timestamp(time.Now()) } // Timestamp converts a time.Time to Unix milliseconds. // From 4147f3e1ad1cf1b7d41699e03c567e2b373fbd14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Sun, 10 Sep 2023 21:39:27 +0300 Subject: [PATCH 2/2] Add local vs UTC `Timestamp(Time)` benchmark Co-authored-by: Peter Bourgon --- ulid_test.go | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/ulid_test.go b/ulid_test.go index 43f81c6..e87568a 100644 --- a/ulid_test.go +++ b/ulid_test.go @@ -834,10 +834,21 @@ func BenchmarkNow(b *testing.B) { func BenchmarkTimestamp(b *testing.B) { now := time.Now() - b.SetBytes(8) - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = ulid.Timestamp(now) + for _, tc := range []struct { + name string + tsfunc func() time.Time + }{ + {"WithLocal", func() time.Time { return now }}, + {"WithUTC", func() time.Time { return now.UTC() }}, //nolint:gocritic // keep lambda for fair comparison + } { + tc := tc + b.Run(tc.name, func(b *testing.B) { + b.SetBytes(8) + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = ulid.Timestamp(tc.tsfunc()) + } + }) } }