I want a busy wait loop for a specific amount of time and I tested the following java code, which gives different outputs on different runs (sometimes). Most of the time it gives 16 and 0. It means one can not trust a busy wait. What is the reason?
public class Testme {
public Testme() {
long start = System.currentTimeMillis();
for (int i = 0; i < 10000000L; i++) {}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
public static void main(String[] args) {
new Testme();
}
}
You definitely can't in such way. Not only that it's unreliable and inconsistent across various processors but can be easily optimized out by JIT.