+ 25
What loop is faster and why?
11 Réponses
+ 19
#include <stdio.h>
#include <sys/time.h>
long long timeInMilliseconds(void) {
struct timeval tv;
gettimeofday(&tv,NULL);
return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
}
int main() {
int _cycles = 100000000, i=0;
long long _t1,
_t2,
_t3;
long long d1, d2;
_t1 = timeInMilliseconds();
while ( i++ < _cycles ) ;
_t2 = timeInMilliseconds();
while ( _cycles-- ) ;
_t3 = timeInMilliseconds();
d1 = _t2 - _t1;
d2 = _t3 - _t2;
printf("D1:%ld\n", d1);
printf("D2:%ld\n", d2);
return 0;
}
+ 19
In my opinion D2 should be less than D1, because of comparing with zero in the second while(){}
+ 13
I think a "for" loop might be a few nano- seconds faster than a "while" loop, maybe because of the extra increment line in the while (generally speaking).
+ 7
@blake you're right about the while loop that more can be done with it, making it more accurate. I was basing my "guesstimate" about the for loop being faster on a program I wrote comparing both types. After 2 billion loops, for some reason the while loop took about a second longer. I didn't have any good way to test this except to count to myself 1-1000, 2-1000, etc. I didn't think the testing was precise enough, so I didn't keep the program. Maybe I'll check into it again. This could be a good challenge!
+ 5
nested for loop is slower for sure.
and for is fastest
+ 4
for is faster than while loop in c#.for loop is averaged about 2.95 to 3.02ms.while loop is average about 3.05 to 3.37ms.
+ 3
So, I've tested the code and the result is the same. d1 is equal to d2. d1 = d2. The first while has to increment and compare. The second has to decrement and compare. The time to increment i++ is the same to decrement _cycles--. The time to compare too.
But, I think, the compile could optimize the second while, then, d2 will be less than d1, indeed. It's not the case. It will be possible in assembly language, I think.
+ 3
while loop is the faster one as it is simple and accurate.
+ 2
I think while loop produces more clear code. As for the speed: i think it is the same.
So I opt for the while loop
+ 1
while is faster since it test the conditions first
0
for loop is more faster than any other loop