Skip to content

byterio/timecache

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Timecache

Go Version License GoDoc Go 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"
)

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)
	}
}

Benchmarks

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

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

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.