-
-
Save nigel-v-thomas/5280590 to your computer and use it in GitHub Desktop.
Measures the maximum observed drift between the millisecond timer and the nano timer (which will usually be provided by Time Stamp Counter). Src - "The Well-Grounded Java Developer" (Listing 6.1, pg. 165), see related post on java simon google group http://goo.gl/GL4qOR
This file contains 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
package uk.me.nvt.PerformanceNanoTimeDrift; | |
/** | |
* Measures the maximum observed drift between the millisecond timer and the nano timer | |
* (which will usually be provided by Time Stamp Counter). | |
* Src - "The Well-Grounded Java Developer" (Listing 6.1, pg. 165) | |
*/ | |
public class App { | |
public static void main(String[] args) { | |
System.out.println("Hello World!"); | |
runWithSpin(args); | |
} | |
private static void runWithSpin(String[] args) { | |
long nowNanos = 0, startNanos = 0; | |
long startMillis = System.currentTimeMillis(), nowMillis = startMillis; | |
int count = 0; | |
while (startMillis == nowMillis) { // runs at least once, until millisecond has increased | |
startNanos = System.nanoTime(); | |
nowMillis = System.currentTimeMillis(); | |
++ count; | |
} | |
System.out.println("Number of cycles until millisecond increase "+count); | |
startMillis = nowMillis; // reset startMillis to increment millisecond | |
double maxDrift = 0; | |
long lastMillis; | |
while (true) { | |
lastMillis = nowMillis; | |
while (nowMillis - lastMillis < 1000) { // while difference between current and previous is less than 1000 | |
nowNanos = System.nanoTime(); | |
nowMillis = System.currentTimeMillis(); | |
} | |
long durationMillis = nowMillis - startMillis; | |
// difference between nanotime (TSC) and millisecond wall clock | |
double driftNanos = 1000000 * (((double) (nowNanos - startNanos)) / 1000000 - durationMillis); | |
if (Math.abs(driftNanos) > maxDrift) { | |
System.out.println("Now - Start = " + durationMillis | |
+ " driftNanos = " + driftNanos); | |
maxDrift = Math.abs(driftNanos); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment