-1

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.

Willchill
  • 13
  • 2
  • _timeneeded is equal to -3 after the loop has completed, which doesn't make any sense_ It does. You should do `endTime - startTime` to get the elapsed time, not `startTime - endTime`. `endTime` will always be greater than `startTime`. – BackSlash Apr 16 '14 at 12:32

3 Answers3

4

You should use:

long timeneeded = endTime - startTime;

As you expect endTime to be bigger :)

BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
0

replace startTime - endTime; with endTime- startTime ;

Gautam
  • 3,276
  • 4
  • 31
  • 53
0

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.

CodeCamper
  • 6,609
  • 6
  • 44
  • 94