lib/fasttime: remove performance overhead when UnixTimestamp() is called from benchmark loops

Move the synctest-related implementation into a separate file protected with go:build goexperiment.synctest.

This is a follow-up for the commit 06c26315df
Updates https://github.com/VictoriaMetrics/VictoriaMetrics/pull/8740
This commit is contained in:
Aliaksandr Valialkin
2025-06-21 12:09:52 +02:00
parent 274e38ebee
commit c2c6f97bd3
3 changed files with 46 additions and 37 deletions

View File

@@ -1,42 +1,5 @@
package fasttime
import (
"testing"
"time"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/atomicutil"
)
func init() {
go func() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for tm := range ticker.C {
t := uint64(tm.Unix())
currentTimestamp.Store(t)
}
}()
}
var currentTimestamp = func() *atomicutil.Uint64 {
var x atomicutil.Uint64
x.Store(uint64(time.Now().Unix()))
return &x
}()
// UnixTimestamp returns the current unix timestamp in seconds.
//
// It is faster than time.Now().Unix()
func UnixTimestamp() uint64 {
if testing.Testing() {
// When executing inside the tests, use the time package directly.
// This allows to override time using synctest package.
return uint64(time.Now().Unix())
}
return currentTimestamp.Load()
}
// UnixDate returns date from the current unix timestamp.
//
// The date is calculated by dividing unix timestamp by (24*3600)

View File

@@ -0,0 +1,33 @@
//go:build !goexperiment.synctest
package fasttime
import (
"time"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/atomicutil"
)
func init() {
go func() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for tm := range ticker.C {
t := uint64(tm.Unix())
currentTimestamp.Store(t)
}
}()
}
var currentTimestamp = func() *atomicutil.Uint64 {
var x atomicutil.Uint64
x.Store(uint64(time.Now().Unix()))
return &x
}()
// UnixTimestamp returns the current unix timestamp in seconds.
//
// It is faster than time.Now().Unix()
func UnixTimestamp() uint64 {
return currentTimestamp.Load()
}

View File

@@ -0,0 +1,13 @@
//go:build goexperiment.synctest
package fasttime
import (
"time"
)
// UnixTimestamp returns the current unix timestamp in seconds.
func UnixTimestamp() uint64 {
// Fall back to time.Now().Unix(), since this is needed for synctest.
return uint64(time.Now().Unix())
}