0
# include <stdio.h>
# include<time.h>
# include <limits.h>

int main() {
    clock_t start;
    long a = 0;
    long b = 0;

    start = clock();
    for (int i = 0; i < INT_MAX; i++) {
        for (int j = 0; j < INT_MAX; j++) {
            for (int k = 0; k < INT_MAX; k++) {
                for (int q = 0; q < INT_MAX; q++) {
                    b = 1;
                }
            }
        }       
    }
    printf("%.5f\n", ((float)(clock() - start) / CLOCKS_PER_SEC));

    start = clock();
    for (int i = 0; i < INT_MAX; i++) {
        for (int j = 0; j < INT_MAX; j++) {
            for (int k = 0; k < INT_MAX; k++) {
                a = 0;
                for (int q = 0; q < INT_MAX; q++) {
                    a += 1;
                }
            }
        }
    }
    printf("%.5f\n",((float)(clock()-start)/CLOCKS_PER_SEC));   
}

When I run in release mode, this shows the result immediately. But when I run in Debug mode, it's not over.

I know that release mode is fast, but how can it be so fast?

sepp2k
  • 363,768
  • 54
  • 674
  • 675
최용석
  • 9
  • 1

2 Answers2

6

When optimizing the compiler may see that this code:

for (int i = 0; i < INT_MAX; i++) {
    for (int j = 0; j < INT_MAX; j++) {
        for (int k = 0; k < INT_MAX; k++) {
            for (int q = 0; q < INT_MAX; q++) {
                b = 1;
            }
        }
    }       
}

can simply be replaced by

b = 1;

Likewise the second loop block can be optimized away.

Further since a and b isn't used, the loops can be completely removed.

So your whole program may be optimized into something representing:

int main() {
    clock_t start;
    start = clock();
    printf("%.5f\n", ((float)(clock() - start) / CLOCKS_PER_SEC));
    start = clock();
    printf("%.5f\n",((float)(clock()-start)/CLOCKS_PER_SEC));   
}
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
1

To expand on this answer, even if you do use a and b, like in a printf statement after the nested loops, the loops can still be optimized away. Why?

Your loop limit is a constant which is known at compile time. So the compiler will actually do the calculation of what a will be in the end at compile time.

Try reading in a loop limit value from the console, and you will see that the second loop now will not be optimized away anymore.

But do not use a huge number like MAX_INT, because that will take very, very long - even on a fast machine. That is why you observe this:

But when I run in Debug mode, it's not over.

The program seems to run forever, right?

A number around 1000 will give you reasonable, measurable times.

GermanNerd
  • 643
  • 5
  • 12