Timing { private Timing() { nanoTimeRef = TimeSource.nanoTime(); currentTimeMillisRef = System.currentTimeMillis(); } private  Timing(); @JmxExport static void updateTiming(); long fromNanoTimeToEpochMillis(final long nanoTime); Instant fromNanoTimeToInstant(final long nanoTime); long fromEpochMillisToNanoTime(final long epochTimeMillis); static Timing getCurrentTiming(); @JmxExport static void stopUpdate(); @Override String toString(); static final long MAX_MS_SPAN; }
@Test public void testTiming() { Assume.assumeFalse(TestUtils.isExecutedInTravis()); long nanoTime = TimeSource.nanoTime(); Instant inst = Instant.now(); Timing currentTiming = Timing.getCurrentTiming(); long currNanos = TimeSource.nanoTime(); long currMillis = System.currentTimeMillis(); long millisInTheFutureCalculated = currentTiming.fromNanoTimeToEpochMillis(currNanos + TimeUnit.MILLISECONDS.toNanos(10)); Assert.assertTrue(currMillis + 10 - millisInTheFutureCalculated <= 1); long fromEpochMillisToNanoTime = currentTiming.fromEpochMillisToNanoTime(Long.MAX_VALUE); Assert.assertTrue(fromEpochMillisToNanoTime - TimeSource.nanoTime() > 0); currNanos = TimeSource.nanoTime(); long nanoTimeIn100ms = currentTiming.fromEpochMillisToNanoTime(System.currentTimeMillis() + 100); long expectNanoTimeIn100ms = currNanos + TimeUnit.MILLISECONDS.toNanos(100); Assert.assertTrue("expected = " + expectNanoTimeIn100ms + ", actual =" + nanoTimeIn100ms, Math.abs(expectNanoTimeIn100ms - nanoTimeIn100ms) < TimeUnit.MILLISECONDS.toNanos(1)); Instant instant = currentTiming.fromNanoTimeToInstant(nanoTime); BigInteger oneMil = BigInteger.valueOf(1000000000L); BigInteger i1 = BigInteger.valueOf(instant.getEpochSecond()).multiply(oneMil) .add(BigInteger.valueOf(instant.getNano())); BigInteger i2 = BigInteger.valueOf(inst.getEpochSecond()).multiply(oneMil) .add(BigInteger.valueOf(inst.getNano())); BigInteger diff = i2.subtract(i1).abs(); Assert.assertTrue("Diff is " + diff, diff.compareTo(BigInteger.valueOf(2000000)) < 0); }