我们的计算机科学老师曾经说过,由于某些原因,倒计时比计数更有效率.例如,如果你需要使用FOR循环并且某个地方没有使用循环索引(比如在屏幕上打印一行N*),我的意思是这样的代码:
for (i = N; i >= 0; i--)
putchar('*');
Run Code Online (Sandbox Code Playgroud)
比以下更好:
for (i = 0; i < N; i++)
putchar('*');
Run Code Online (Sandbox Code Playgroud)
这是真的吗?如果是这样,有谁知道为什么?
我刚刚开始学习汇编并制作一些自定义循环,用于使用C++的asm {}体交换两个变量,使用C-Free 5.0中的Digital-Mars编译器
启用-o(优化)
并得到了结果:
time of for-loop(cycles) 844
time of while-loop(cycles) 735
time of custom-loop-1(cycles) 562
time of custom-loop-2(cycles) 469
Run Code Online (Sandbox Code Playgroud)
我无法找到Digital-Mars编译器"asm output"选项进行比较.构建选项中没有其他优化选项.我应该改变我的编译器吗?如果是的话,哪一个?你能看一下下面的代码并告诉我为什么自定义循环更快?
这是循环的标准:
t1=clock();
for(int i=0;i<200000000;i++)
{
temp=a;//instruction 1
a=b;//instruction 2
b=temp;//3 instructions total
}
t2=clock();
printf("\n time of for-loop(increasing) %i \n",(t2-t1));
Run Code Online (Sandbox Code Playgroud)
这是标准的while循环:
t1=clock();
while(j<200000000)
{
temp=a;//again it is three instructions
a=b;
b=temp;
j++;
}
t2=clock();
printf("\n time of while-loop(cycles) %i \n",(t2-t1));
Run Code Online (Sandbox Code Playgroud)
这是我的自定义循环1:
t1=clock();
j=200000000;//setting the count
__asm
{
pushf //backup
push eax //backup
push ebx //backup
push ecx …Run Code Online (Sandbox Code Playgroud)