Features • Quick Start • Performance • Usage • API Reference • Documentation
Complete documentation is available at: https://agilira.github.io/go-timecache/
Part of our Xantos Core, go-timecache provides zero-allocation access to cached time values, eliminating the performance overhead of repeated time.Now() calls in high-throughput scenarios like logging, metrics collection, and real-time data processing.
- Zero-allocation time access: Get current time without heap allocations
- Configurable precision: Choose your ideal balance between accuracy and performance
- Thread-safe: Safe for concurrent use from multiple goroutines
- Simple API: Drop-in replacement for
time.Now()with minimal code changes - Multiple formats: Access time as
time.Time, nanoseconds, or formatted string
go-timecache is designed for Go 1.23+ environments and follows Long-Term Support guidelines to ensure consistent performance across production deployments.
Benchmarks show dramatic improvements over standard time.Now():
AMD Ryzen 5 7520U with Radeon Graphics
BenchmarkTimeNow-8 25118025 42.98 ns/op 0 B/op 0 allocs/op
BenchmarkCachedTime-8 1000000000 0.3549 ns/op 0 B/op 0 allocs/op
BenchmarkCachedTimeNano-8 1000000000 0.3574 ns/op 0 B/op 0 allocs/op
BenchmarkTimeNowUnixNano-8 27188656 42.68 ns/op 0 B/op 0 allocs/op
BenchmarkCachedTimeParallel-8 1000000000 0.1737 ns/op 0 B/op 0 allocs/op
BenchmarkTimeNowParallel-8 184139052 6.417 ns/op 0 B/op 0 allocs/op
Reproduce benchmarks:
go test -bench=. -benchmemCachedTimeis ~121x faster thantime.Now()CachedTimeParallelis ~37x faster than paralleltime.Now()- Zero heap allocations in all operations
go get github.com/agilira/go-timecacheimport "github.com/agilira/go-timecache"
// Using the default global cache
now := timecache.CachedTime()
nanos := timecache.CachedTimeNano() // Zero allocation!
// Create your own cache with custom settings
tc := timecache.NewWithResolution(1 * time.Millisecond)
defer tc.Stop() // Important: remember to stop when done
customTime := tc.CachedTime()CachedTime() time.Time: Get current time from default cacheCachedTimeNano() int64: Get nanoseconds since epoch (zero allocation)CachedTimeString() string: Get formatted time stringDefaultCache() *TimeCache: Access the default TimeCache instanceStopDefaultCache(): Stop the default cache (use during shutdown)
New() *TimeCache: Create a new cache with default settingsNewWithResolution(resolution time.Duration) *TimeCache: Custom resolutionCachedTime() time.Time: Get current time from this cacheCachedTimeNano() int64: Get nanoseconds from this cache (zero allocation)CachedTimeString() string: Get formatted time from this cacheResolution() time.Duration: Get this cache's resolutionStop(): Stop this cache's background updater
https://agilira.github.io/go-timecache/
go-timecache is licensed under the Mozilla Public License 2.0.
go-timecache • an AGILira library