Skip to content

Commit

Permalink
time: do not export timestamp var, instead provide helper function to…
Browse files Browse the repository at this point in the history
  • Loading branch information
leonklingele committed Nov 14, 2022
1 parent e2e2338 commit 0763c33
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
14 changes: 9 additions & 5 deletions time.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,28 @@ import (

var (
timestampTimer sync.Once
// Timestamp please start the timer function before you use this value
// please load the value with atomic `atomic.LoadUint32(&utils.Timestamp)`
Timestamp uint32
timestamp uint32
)

// Timestamp returns the current time.
// Make sure to start the updater once using StartTimeStampUpdater() before calling.
func Timestamp() uint32 {
return atomic.LoadUint32(&timestamp)
}

// StartTimeStampUpdater starts a concurrent function which stores the timestamp to an atomic value per second,
// which is much better for performance than determining it at runtime each time
func StartTimeStampUpdater() {
timestampTimer.Do(func() {
// set initial value
atomic.StoreUint32(&Timestamp, uint32(time.Now().Unix()))
atomic.StoreUint32(&timestamp, uint32(time.Now().Unix()))
go func(sleep time.Duration) {
ticker := time.NewTicker(sleep)
defer ticker.Stop()

for t := range ticker.C {
// update timestamp
atomic.StoreUint32(&Timestamp, uint32(t.Unix()))
atomic.StoreUint32(&timestamp, uint32(t.Unix()))
}
}(1 * time.Second) // duration
})
Expand Down
8 changes: 4 additions & 4 deletions time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ func Test_TimeStampUpdater(t *testing.T) {
StartTimeStampUpdater()

now := uint32(time.Now().Unix())
checkTimeStamp(t, now, atomic.LoadUint32(&Timestamp))
checkTimeStamp(t, now, Timestamp())
// one second later
time.Sleep(1 * time.Second)
checkTimeStamp(t, now+1, atomic.LoadUint32(&Timestamp))
checkTimeStamp(t, now+1, Timestamp())
// two seconds later
time.Sleep(1 * time.Second)
checkTimeStamp(t, now+2, atomic.LoadUint32(&Timestamp))
checkTimeStamp(t, now+2, Timestamp())
}

func Benchmark_CalculateTimestamp(b *testing.B) {
Expand All @@ -34,7 +34,7 @@ func Benchmark_CalculateTimestamp(b *testing.B) {
var res uint32
b.Run("fiber", func(b *testing.B) {
for n := 0; n < b.N; n++ {
res = atomic.LoadUint32(&Timestamp)
res = atomic.LoadUint32(&timestamp)
}
checkTimeStamp(b, uint32(time.Now().Unix()), res)
})
Expand Down

0 comments on commit 0763c33

Please sign in to comment.