1s内能执行多少次for循环

365bet赌城网址 🌸 2025-10-10 07:55:01 🎨 admin 👁️ 5047 ❤️ 286
1s内能执行多少次for循环

这道题还可以这样来问 for(;;) 和 while(true) 哪一种效率会高一些?

这里用到了GetTickCount()函数 测试某个函数的效率时 会经常使用

DWORD startTick = GetTickCount();

// do func xx

DWORD endTick = GetTickCount();

int elapseSec = (endTick - startTick)/1000; // 耗时xx秒

那1s能执行多少次for循环呢?

#include

#include

int main()

{

DWORD startTick = GetTickCount();

int i = 0;

for(;;i++)

{

DWORD endTick = GetTickCount();

if((endTick - startTick)/1000 >= 1) break;

}

printf("i = %d\n", i);

system("pause");

return 0;

}

测试截图:

如果使用while(true)呢?

#include

#include

int main()

{

DWORD startTick = GetTickCount();

int i = 0;

while(true)

{

i++;

DWORD endTick = GetTickCount();

if((endTick - startTick)/1000 >= 1) break;

}

printf("i = %d\n", i);

system("pause");

return 0;

}

测试截图:

可以看出1s内for(;;)是比while(true)循环的次数要多的,从原理上解释,for(;;)是空语句,指令少,不占用寄存器,没有判断跳转,比while(true)简洁明了

ps:有兴趣的同学可以看看他们的汇编代码就更能了解它们的差异了。

相关推荐