下面是两段功能一样的代码:
c++:
        int count=0;
int t1=::GetTickCount();
for(int i=0;i<50000000;i++){
         count+=i;
}
CString str;
str.Format("%i  %i",count,::GetTickCount()-t1);
AfxMessageBox(str);内联汇编:
        int count=0;
int t1=::GetTickCount();
__asm{
mov ecx,50000000d;
mov ebx,count;
     DJ: mov eax,50000000d;
sub eax,ecx;
add ebx,eax;
loop DJ;
mov count,ebx
}
CString str;
str.Format("%i  %i",count,::GetTickCount()-t1);
AfxMessageBox(str);在debug模式下两段执行时间是一样的,但在发行模式下,c++那段的要比内联汇编段快一倍.不解中...
另外内联汇编段调试和发行模式用的时间是一样的.
求教高人给个解释.

解决方案 »

  1.   

    试试下面的,另外内联汇编一定会比C++的快吗?呵呵,不一定吧
    __asm{
    mov ebx,count
    mov eax,0
    DJ:
      add ebx,eax
      add eax,1  
      cmp eax,50000000d
    jne DJ 
    mov count,ebx
    }
      

  2.   

    是你的内联汇编写得不好,你不妨这样,在for上面下个断点,然后跑起来,断下,按下Ctrl+K就能看到VC提供的汇编代码了,绝对不是你那样的。你换成VC写的汇编那样的话,肯定是一样快的如果你优化了下汇编代码,那么一定比C的代码块
      

  3.   

    测试一下
    int count=0; 
    int t1=::GetTickCount(); 
    __asm//一般的思路
    {
    xor ecx,ecx
    mov eax,count
    DJ:
    add eax,ecx
    inc ecx
    cmp ecx,50000000
    jne DJ
    mov count,eax
    }
    CString str; 
    str.Format("%i  %i",count,::GetTickCount()-t1); 
    AfxMessageBox(str);
    结果:1283106752  31再看优化后的:
    int count=0; 
    int t1=::GetTickCount(); 
    __asm
    {
    MOV EDI,count
    XOR EAX,EAX
    XOR ESI,ESI
    XOR EDX,EDX
    XOR ECX,ECX
    DJ:
    ADD EDI,EAX
    LEA ECX,DWORD PTR DS:[ECX+EAX+1]
    LEA EDX,DWORD PTR DS:[EDX+EAX+2]
    LEA ESI,DWORD PTR DS:[ESI+EAX+3]
    ADD EAX,4
    CMP EAX,2FAF080h
    JL DJ
    ADD ESI,ECX
    ADD ESI,EDX
    ADD EDI,ESI
    MOV count,EDI
    }
    CString str; 
    str.Format("%i  %i",count,::GetTickCount()-t1); 
    AfxMessageBox(str);
    结果:1283106752  16
      

  4.   

    3楼很猛.还用异或来清0,见识了.
    最近刚学习汇编没多久,刚看到循环这里,就试了下,看了1,3楼的代码我才知道loop是那么慢,%80-90的时间都花在loop语句中,书上居然还推荐使用..小d不才,各位看官见笑了.3楼优化后确实快,我来研究一下...