循环想必各位都有用过,那么用哪个循环效率最高呢,现在就来实际检测
测试代码如下
#include<iostream> #include<time.h> using namespace std; #define cycs 500 int main(int argc,char* argv[]) { double avg = 0; int i = cycs; while (i--) {//for循环1号 int f = clock(); for (int a = 0; a < 9999999; a++); int s = clock(); avg += ((double)s - (double)f); } cout << avg / cycs <<endl; avg = 0; i = cycs; while (i--) {//for循环2号 int f = clock(); for (int a = 1; a <= 9999999; a++); int s = clock(); avg += ((double)s - (double)f); } cout << avg / cycs << endl; avg = 0; i = cycs; while (i--) {//while循环 int f = clock(); int a = 0; while (a < 9999999) a++; int s = clock(); avg += ((double)s - (double)f); } cout << avg / cycs<<endl; avg = 0; i = cycs; while (i--) {//dowhile循环 int f = clock(); int a = 0; do { a++; } while (a < 9999999); int s = clock(); avg += ((double)s - (double)f); } cout << avg / cycs<<endl; }
每次循环9999999次,反复运行500次取平均时间
第一轮测试结果如下,在调试模式下执行
17.054 15.276 13.15 14.916 /////// 16.384 13.72 11.854 13.966 /////// 17.194 14.204 11.79 13.56 ////// 16.644 13.646 12.964 14.028
综合while循环最快
第二轮测试结果如下,在非调试模式下执行
14.134 14 14.382 15.09 ////// 15.444 17.222 16.738 16.222 /////// 15.384 15.294 14.366 14.636 ////// 13.78 13.24 14.568 14.608
综合4者,4者的速度并没有太大差别
从汇编角度分析
//for循环1号,3次mov,2次jmp,1次add,1次cmp,1次jge,8条指令 mov dword ptr [ebp-34h],0 jmp main+80h (04B2EB0h) mov eax,dword ptr [ebp-34h] add eax,1 mov dword ptr [ebp-34h],eax cmp dword ptr [ebp-34h],98967Fh jge main+8Bh (04B2EBBh) jmp main+77h (04B2EA7h) //for循环2号,3次mov,2次jmp,1次cmp,1次jg,8条指令 mov dword ptr [ebp-58h],1 jmp main+145h (04B2F75h) mov eax,dword ptr [ebp-58h] add eax,1 mov dword ptr [ebp-58h],eax cmp dword ptr [ebp-58h],98967Fh jg main+150h (04B2F80h) jmp main+13Ch (04B2F6Ch) //while循环,3次mov,1次cmp,1次jge,1次add,1次jmp,7条指令 mov dword ptr [ebp-7Ch],0 cmp dword ptr [ebp-7Ch],98967Fh jge main+213h (04B3043h) mov eax,dword ptr [ebp-7Ch] add eax,1 mov dword ptr [ebp-7Ch],eax jmp main+1FFh (04B302Fh) //dowhile循环,3次mov,1次add,1次cmp,1次jl,6条指令 mov dword ptr [ebp-0A0h],0 mov eax,dword ptr [ebp-0A0h] add eax,1 mov dword ptr [ebp-0A0h],eax cmp dword ptr [ebp-0A0h],98967Fh jl main+2CEh (04B30FEh)
虽然for循环指令较多,但是整体时序较快,而dowhile虽然指令较少,但是时序较慢
所以实际上,各个循环的速度并没有什么差别,虽然在调试模式下会有1~2ms的差别,但是在循环次数达到9999999的情况下
基本可以说是没有差别,也不用担心<=比<更耗时间,怎么舒服就怎么用