Skip to content

Repository files navigation

Timecache

Go VersionLicenseGoDocGo Report Card

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.

Why

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.

Features

  • ⚡ 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.

Installation

go get -u github.com/byterio/timecache

Usage

package main
import (
"fmt""time""github.com/byterio/timecache"
)
funcmain() {
tc:=timecache.New()
tc.Start()
defertc.Stop()
fori:=0; i<5; i++ {
fmt.Println("cached unix:", tc.Timestamp())
time.Sleep(500*time.Millisecond)
}
}

Benchmarks

Benchmark on an Intel Core i7-6700HQ CPU @ 2.60GHz:

BenchmarkIterationsns/opB/opallocs/op
Benchmark_CalculateTimestamp/timecache-81,000,000,0001.00700
Benchmark_CalculateTimestamp/default-8100,000,00010.1200
Benchmark_CalculateTimestamp/timecache_asserted-81,579,101773.1122
Benchmark_CalculateTimestamp/default_asserted-81,546,180779.982

Feedback and Contributions

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.

Support

If you enjoy using Timecache, please consider giving it a star! Your support helps others discover the project and encourages further development.

License

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.