Created
August 2, 2012 16:15
-
-
Save hoffrocket/3238310 to your computer and use it in GitHub Desktop.
higher precision currentTime in java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static org.junit.Assert.*; | |
import org.junit.Test; | |
public class TimeTest { | |
private final static long nanoTimeOffset = (System.currentTimeMillis() * 1000000) - System.nanoTime(); | |
public static long currentTimeNanos() { | |
return System.nanoTime() + nanoTimeOffset; | |
} | |
public static long currentTimeMicros() { | |
return currentTimeNanos() / 1000; | |
} | |
public static void assertMaxDiff(long expected, long actual, long diff) { | |
assertTrue("difference between " + expected + " and " + actual + " greater than " + diff, | |
Math.abs(expected - actual) <= diff); | |
} | |
@Test | |
public void testCurrentTimeNanos() { | |
assertMaxDiff(System.currentTimeMillis(), currentTimeNanos() / 1000000, 1); | |
} | |
@Test | |
public void testCurrentTimeMicros() { | |
assertMaxDiff(System.currentTimeMillis(), currentTimeMicros() / 1000, 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment