Skip to content

Commit

Permalink
improved the timer precision, the minimal resolution is now 1ms inste…
Browse files Browse the repository at this point in the history
…ad of 1s
  • Loading branch information
flrdv committed Nov 6, 2024
1 parent ea9e075 commit 76eaea1
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions internal/timer/timer.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,26 @@ import (
"time"
)

// Time contains the unix-time in milliseconds updated every [Resolution] milliseconds
var Time = new(atomic.Int64)

func Now() time.Time {
return time.Unix(Time.Load(), 0)
millis := Time.Load()
return time.Unix(millis/1000, (millis%1000)*1e6)
}

// Resolution depicts how often is the time updated. By default, it's updated once
// every 500ms which is considered precise enough
// Resolution is the frequency at which time is updated. Default 500ms are
// precise enough for setting I/O deadlines
const Resolution = 500 * time.Millisecond

func init() {
Time.Store(time.Now().Unix())
// there is no guarantee that the goroutine will be started immediately. If it won't,
// some rapid usage of the timer will result in zero-time, which isn't great actually
Time.Store(time.Now().UnixMilli())

go func() {
for {
Time.Store(time.Now().Unix())
Time.Store(time.Now().UnixMilli())
time.Sleep(Resolution)
}
}()
Expand Down

0 comments on commit 76eaea1

Please sign in to comment.