Timecache stores the current Unix timestamp (in seconds) in an atomic variable and periodically refreshes it from a background goroutine. This helps reduce overhead in hot code paths by avoiding repeated time.Now() calls.
Calling time.Now() frequently can add measurable overhead in performance-sensitive sections. Timecache provides a fast, lock-free way to read the current Unix time in seconds.
- ⚡ Fast, lock-free reads using atomic operations.
- 🔄 Background updater with configurable interval.
- 💯 Safe to call
Start()multiple times. - ✨ Clean
Stop()to avoid goroutine leaks and allow restarting.
go get -u github.com/byterio/timecachepackage main
import (
"fmt"
"time"
"github.com/byterio/timecache"
)
func main() {
tc := timecache.New()
tc.Start()
defer tc.Stop()
for i := 0; i < 5; i++ {
fmt.Println("cached unix:", tc.Timestamp())
time.Sleep(500 * time.Millisecond)
}
}| Benchmark | Iterations | ns/op | B/op | allocs/op |
|---|---|---|---|---|
| Benchmark_CalculateTimestamp/timecache-8 | 1,000,000,000 | 1.007 | 0 | 0 |
| Benchmark_CalculateTimestamp/default-8 | 100,000,000 | 10.12 | 0 | 0 |
| Benchmark_CalculateTimestamp/timecache_asserted-8 | 1,579,101 | 773.1 | 12 | 2 |
| Benchmark_CalculateTimestamp/default_asserted-8 | 1,546,180 | 779.9 | 8 | 2 |
If you encounter any issues or have suggestions for improvement, please open an issue on GitHub.
We welcome contributions! Fork the repository, make your changes, and submit a pull request.
If you enjoy using Timecache, please consider giving it a star! Your support helps others discover the project and encourages further development.
Timecache is open-source software released under the Apache License, Version 2.0. You can find a copy of the license in the LICENSE file.