+ 25

What loop is faster and why?

10th Mar 2018, 2:09 PM
Aliaksei Do
Aliaksei Do - avatar
11 odpowiedzi
+ 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; }
10th Mar 2018, 2:10 PM
Aliaksei Do
Aliaksei Do - avatar
+ 19
In my opinion D2 should be less than D1, because of comparing with zero in the second while(){}
10th Mar 2018, 2:37 PM
Aliaksei Do
Aliaksei Do - avatar
+ 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).
10th Mar 2018, 7:22 PM
Eric Zatarack
Eric Zatarack - avatar
+ 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!
11th Mar 2018, 5:47 PM
Eric Zatarack
Eric Zatarack - avatar
+ 5
nested for loop is slower for sure. and for is fastest
12th Mar 2018, 3:34 AM
Muhammad Waqas Aslam
Muhammad Waqas Aslam - avatar
+ 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.
12th Mar 2018, 6:57 AM
Durg@😊
+ 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.
10th Mar 2018, 4:32 PM
aiese
aiese - avatar
+ 3
while loop is the faster one as it is simple and accurate.
11th Mar 2018, 5:28 PM
blake
blake - avatar
+ 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
12th Mar 2018, 12:19 PM
kocsis Zoltán
kocsis Zoltán - avatar
+ 1
while is faster since it test the conditions first
12th Mar 2018, 11:26 AM
JOB KIMELI
JOB KIMELI - avatar
0
for loop is more faster than any other loop
22nd Jul 2018, 9:07 AM
Parv Gour
Parv Gour - avatar