summaryrefslogtreecommitdiff
path: root/util/fasttime.go
blob: f1a81333089d01a2c73c8012a101d389401694d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package util

import (
	"sync/atomic"
	"time"
)

// FastTime provides current unix time using specified resolution with reduced number of syscalls.
type FastTime struct {
	last   int64
	ticker *time.Ticker
}

// NewFastTime returns new time provider with given resolution.
func NewFastTime(resolution time.Duration) *FastTime {
	ft := &FastTime{
		last:   time.Now().UnixNano(),
		ticker: time.NewTicker(resolution),
	}

	go ft.run()

	return ft
}

// Stop ticking.
func (ft *FastTime) Stop() {
	ft.ticker.Stop()
}

// UnixNano returns current timestamps. Value might be delayed after current time by specified resolution.
func (ft *FastTime) UnixNano() int64 {
	return atomic.LoadInt64(&ft.last)
}

// consume time values over given resolution.
func (ft *FastTime) run() {
	for range ft.ticker.C {
		atomic.StoreInt64(&ft.last, time.Now().UnixNano())
	}
}