I'm trying to see how long a snippet of codes takes to execute, however, as mentioned in the title, I get a negative value returned in the terminal.
I've searched stack overflow for this problem, and there were multiple questions the exact same of mine (1) (2), and all of them had the same answers: The clock counters on the different CPU cores could slightly differ from each other, resulting in this strange behavior.
However, these answers were from back in 2010, and since then both windows and java have developed a lot. Since this issue was already fixed back in 2010 on linux, I thought maybe this was also fixed on windows 10 now and my issue might come from a different problem.
That's why I've created this new thread, since there might be a new/different solution.
I'm using windows 10 and openjdk-19, and am using the following code
import java.sql.Timestamp;
public class Main
{
public static void main(String[] args)
{
// gets the time in the beginning
Timestamp begin = new Timestamp(System.currentTimeMillis());
// assigns the number of iterations in the for loop and o to zero
long times = 1000000000;
int o = 0;
// keeps adding 1 to o for "times" times
for (int i = 0; i < times; i++) {
o++;
}
// prints the result of o
System.out.println(o);
// get the end time
Timestamp end = new Timestamp(System.currentTimeMillis());
// compare the 2 times and print it out in milliseconds
System.out.println((end.getNanos() - begin.getNanos()) / 1000000);
}
}
and this is an example of an unexpected result:
1000000000
-298
Process finished with exit code 0
EDIT:
The question has been marked as duplicate, where the answer indicates that System.currentTimeMillis()
causes a +- 15ms difference, but this doesn't answer the fact that it becomes negative and the difference is larger than what was said. Further more, they say to use System.nanoTime()
instead, but this also causes negative results, and only gives numbers in the hundreds like 300 or -200.