tags:

views:

101

answers:

6

On a modern 64-Bit machine, how long do you think it takes to iterate through all the positive long numbers?

Below is a code snippet in Java to demonstrate the idea.

Without running the code yourself, how long do you think this code is going to run?

How long will similar code run in other programming languages?

public class LongLoop {

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        for (long i = 0; i < Long.MAX_VALUE; i++) {
            // do nothing, just loop
        }
        long stopTime = System.currentTimeMillis();
        long duration = stopTime - startTime;
        System.out.println("Time taken: " + duration + " milliseconds");
    }
}
+1  A: 

That depends on a number of things. The processor speed. The language, the compiler. There are too many factors to attempt to guess and have it be reasonably accurate.

Besides what if in my particular language long really represents 0-255? Languages can vary what long actually is.

Kevin
+5  A: 

I'd say 0, because the compiler will remove the loop.

Artefacto
Duration will not print 0 singe there are currentTimeMillis calls, which are not precise and highly depend on OS. But I agree with the general idea.
Juriy
I thought the JIT would optimize away the empty loop. But with the Eclipse compiler and the Sun VM it didn't happen. That's one of the reasons I asked here.
Carl Rosenberger
A: 

About 146 years on my Core 2 Duo.

Ovidiu Pacurar
A: 

In this case the compiler will actually ignore the loop.

medopal
A: 

There are 2 possibilities, depending on your language, compiler and machine.

  • The compiler remove-optimizes the loop: About 0 seconds.
  • The compiler keeps the loop: More than 5 minutes... still running ;)

Oh, and of course you should try to run this in parallel to speed things up!

mafutrct
A: 

The answer is Yes ...but it might take a bit longer

DrDro