Question

Yesterday I was screwing around with Java, and I wrote this application.

public class MaxInt {

    public static void main(String[] args){
        long startTime = System.currentTimeMillis();
        long endTime;
        for(int i = 0; i < 2147483647; i++){
        }
        endTime = System.currentTimeMillis();

        long timeneeded = startTime - endTime;
        System.out.println("It took " + timeneeded + " milliseconds to count to 2,147,483,646.");
    }
}

Strangely, however, timeneeded is equal to -3 after the loop has completed, which doesn't make any sense to me at all. I was just curious as to why, and how, this program could generate time.

Was it helpful?

Solution

You should use:

long timeneeded = endTime - startTime;

As you expect endTime to be bigger :)

OTHER TIPS

replace startTime - endTime; with endTime- startTime ;

I cleaned up your code a bit for you, maybe it will give you some ideas in the future

   public static void main(String[] args) {
    long endTime;
    long startTime = System.currentTimeMillis();
    for (int i = Integer.MAX_VALUE; i > 0; i--) {}
    endTime = System.currentTimeMillis();
    long timeneeded = endTime - startTime;
    System.out.println(MessageFormat.format("It took {0} milliseconds to count to {1}.", timeneeded, Integer.MAX_VALUE));
    }

Also you were not counting to 2,147,483,646 you were counting to 2,147,483,647. Remember in your for loop you made 0 the first number to be counted so you didn't have to add an extra number. Also counting backwards is much more efficient.

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