tags:

views:

65

answers:

1

Can someone explain me the exact interaction in context of delay between the two for loops with clock function. How does for1 interact with for2 on the cout statement(30 on 640000000)?

start=clock();
cout<<endl<<start<<endl;
for(delay=0; delay<30; delay++)
    for(i=0; i<640000000; i++);

end=clock();
cout<<end<<endl;
cout<<"Num of ticks for non reg-loop: ";
cout<<end-start<<'\n';
+2  A: 

Probably a decent optimizer will see that the loop is a no-op and optimize it out completely, so there will be almost no difference between start and end.

If it's not optimized out, the two loops are simply working around the fact that 30*640000000 is bigger than could be stored in a 32-bit integer. It runs the inner 640000000 loop 30 times to attempt to magnify the delay.

EDIT: So for each of 30 times (using variable delay), it creates another loop (using variable i) starting at 0. It then increments i 640000000 times, each increment taking a small fraction of time (if not optimized away). Then the inner loop completes, delay is increased by 1, and the inner loop starts over at 0 again.

EDIT2: If you're just trying to add a delay, have you considered using sleep or usleep or the corresponding Windows function(s) rather than trying to implement a sleep by iteration?

Mark B
In other words how does delay actually work?
are you asking how the for loop is working?
daramarak
So i is incremented so fast thx to the optimizer?
One more thing Mark, I don't understand how does inner for complete its 64000000 iterations so fast (i=0; i<640000000; i++ ). Is it skipped somehow or what?
@learningtolive Exactly. Since there isn't any actual work inside the loop the compiler will remove the entire loop and not do any incrementing at all.
Mark B