Tickers which use System.currentTimeMillis() or nanoTime()
Ticker ticker = Ticker.millis();
// or
Ticker ticker = Ticker.nanos();
double timeInSec = ticker.count() / (double) ticker.countPerSecond();
Ticker for testing purposes
Ticker ticker = Ticker.forTesting()
.count(System.currentTimeMillis());
// or
Ticker ticker = Ticker.forTesting()
.count(System.currentTimeMillis() * 1000)
.countPerSecond(1_000_000)
.countFromEpoch(0);
double timeInSecs = ticker.count() / (double) ticker.countPerSecond();
Ticker which uses a high resolution time
Ticker ticker = Ticker.highResolution();
long start = ticker.count();
// do some work
long end = ticker.count();
double timeInSecs = (double) (end - start) / ticker.countPerSecond();
// or
long timeInMicros = (end - start) * 1_000 / ticker.countPerSecond();
// or
long timeInMillis = (end - start) * 1_000_000 / ticker.countPerSecond();
Ticker |
Latency |
Ticker.nanos().count() |
14.8 ns |
Ticker.highResolution().count() |
6.8 ns |
Example from tests
Ticker instance = ...
long epochOffset = instance.countFromEpoch();
long epochTicks = instance.count() + epochOffset;
long epochMillis = epochTicks / (instance.countPerSecond() / 1000);
long diffMillis = epochMillis - System.currentTimeMillis();
Assert.assertTrue(Math.abs(diffMillis) < 1000);