Skip to content

Instantly share code, notes, and snippets.

@tomwhoiscontrary
Created November 6, 2017 13:04
Show Gist options
  • Save tomwhoiscontrary/20ad3bba290ebdd934ddf50ba48a8d08 to your computer and use it in GitHub Desktop.
Save tomwhoiscontrary/20ad3bba290ebdd934ddf50ba48a8d08 to your computer and use it in GitHub Desktop.
Works out the correspondence between currentTimeMillis and nanoTime
import java.util.Arrays;
public class Time {
public static void main(String[] args) throws InterruptedException {
int n = 100;
int[] before = new int[n];
int[] after = new int[n];
// warmup
for (int i = 0; i < n; i++) {
go(before, after, i);
}
for (int i = 0; i < n; i++) {
go(before, after, i);
}
Arrays.sort(before);
Arrays.sort(after);
int beforeBound = before[n / 2];
int afterBound = after[n / 2];
int offsetWithinMilli = (beforeBound + afterBound) / 2;
System.out.println(offsetWithinMilli);
long millis = System.currentTimeMillis();
long nanos = System.nanoTime();
long milliInNanos = millis * 1_000_000;
long startOfMilli = nanos - offsetWithinMilli;
long offset = milliInNanos - startOfMilli;
Thread.sleep(100);
long nanoTime = System.nanoTime();
long currentTimeMillis = System.currentTimeMillis();
System.out.println(nanoTime + " + " + offset + " = " + (nanoTime + offset) + " -> " + (nanoTime + offset) / 1_000_000 + " == " + currentTimeMillis);
}
private static void go(int[] before, int[] after, int i) {
long milliBefore = System.currentTimeMillis();
long nanoBefore = System.nanoTime();
long milliAfter;
long nanoAfter;
while (true) {
long milliTime = System.currentTimeMillis();
long nanoTime = System.nanoTime();
if (milliTime == milliBefore) {
nanoBefore = nanoTime;
} else {
nanoAfter = nanoTime;
milliAfter = milliTime;
break;
}
}
if (milliAfter - milliBefore > 1) return;
before[i] = (int) (nanoBefore % 1_000_000);
after[i] = (int) (nanoAfter % 1_000_000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment