Why does it take so much longer to loop through 10 billion than 1 billion?

c, for-loop, loops

Solution

I guess `i` is a 32-bit integer variable and is therefore always smaller than 10 billion (which is more than 2^32), whereas 1 billion still fits into the 32-bit range (which ends at about 2 or 4 billion, depending on signedness). Though I don't know how the compiler promotes this 10 billion constant, but he seems to realize the overflow issue and makes it an infite loop.

What happens when you make `i` a `long long int` (and maybe the `10000000000` a `10000000000L`, but that seems to be no problem)?

Problem

Why does this loop (to 1 billion) only take a few sounds to execute ... ``` for (i = 0; i < 1000000000; i++) { } ``` ... but this loop (to 10 billion) takes >10 minutes? ``` for (i = 0; i < 10000000000; i++) { } ``` Shouldn't it just take 30 seconds or so (3 seconds x 10)?

Original source

Related problems