Question

This simple code snippet output is in the range of 11 - 13 milli seconds. Now assuming for sake of question, that an increment of x is just a single instruction, the 2.3Ghz cpu of mind should take rougly a second to execute, since value of intMAX is close of 2 billion. Why is the answer in order of few milli's (11 - 13 millis) rather than in order of seconds (900 millis - 1100 millis) ??

    long time1 = System.currentTimeMillis();
    int x = 0;
    while (x < Integer.MAX_VALUE) {
        x++;
    }
    System.out.println(System.currentTimeMillis() - time1);
Was it helpful?

Solution

In theory - this can be optimized down to x=Integer.MAX_VALUE and then if x is not used after, completely removed

it is getting harder and harder to test how long things take since they get optimized out, especially if unused

try setting x to different start values and using x after the timer in a print or other calculation that leads to a print

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top