Skip to content

Instantly share code, notes, and snippets.

@hoffrocket
Created August 2, 2012 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoffrocket/3238310 to your computer and use it in GitHub Desktop.
Save hoffrocket/3238310 to your computer and use it in GitHub Desktop.
higher precision currentTime in java
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