Note that there are some explanatory texts on larger screens.

plurals
  1. POIs inline assembly language slower than native C++ code?
    primarykey
    data
    text
    <p>I tried to compare the performance of inline assembly language and C++ code, so I wrote a function that add two arrays of size 2000 for 100000 times. Here's the code:</p> <pre><code>#define TIMES 100000 void calcuC(int *x,int *y,int length) { for(int i = 0; i &lt; TIMES; i++) { for(int j = 0; j &lt; length; j++) x[j] += y[j]; } } void calcuAsm(int *x,int *y,int lengthOfArray) { __asm { mov edi,TIMES start: mov esi,0 mov ecx,lengthOfArray label: mov edx,x push edx mov eax,DWORD PTR [edx + esi*4] mov edx,y mov ebx,DWORD PTR [edx + esi*4] add eax,ebx pop edx mov [edx + esi*4],eax inc esi loop label dec edi cmp edi,0 jnz start }; } </code></pre> <p>Here's <code>main()</code>:</p> <pre><code>int main() { bool errorOccured = false; setbuf(stdout,NULL); int *xC,*xAsm,*yC,*yAsm; xC = new int[2000]; xAsm = new int[2000]; yC = new int[2000]; yAsm = new int[2000]; for(int i = 0; i &lt; 2000; i++) { xC[i] = 0; xAsm[i] = 0; yC[i] = i; yAsm[i] = i; } time_t start = clock(); calcuC(xC,yC,2000); // calcuAsm(xAsm,yAsm,2000); // for(int i = 0; i &lt; 2000; i++) // { // if(xC[i] != xAsm[i]) // { // cout&lt;&lt;"xC["&lt;&lt;i&lt;&lt;"]="&lt;&lt;xC[i]&lt;&lt;" "&lt;&lt;"xAsm["&lt;&lt;i&lt;&lt;"]="&lt;&lt;xAsm[i]&lt;&lt;endl; // errorOccured = true; // break; // } // } // if(errorOccured) // cout&lt;&lt;"Error occurs!"&lt;&lt;endl; // else // cout&lt;&lt;"Works fine!"&lt;&lt;endl; time_t end = clock(); // cout&lt;&lt;"time = "&lt;&lt;(float)(end - start) / CLOCKS_PER_SEC&lt;&lt;"\n"; cout&lt;&lt;"time = "&lt;&lt;end - start&lt;&lt;endl; return 0; } </code></pre> <p>Then I run the program five times to get the cycles of processor, which could be seen as time. Each time I call one of the function mentioned above only.</p> <p>And here comes the result.</p> <h2>Function of assembly version:</h2> <pre><code>Debug Release --------------- 732 668 733 680 659 672 667 675 684 694 Average: 677 </code></pre> <h2>Function of C++ version:</h2> <pre><code>Debug Release ----------------- 1068 168 999 166 1072 231 1002 166 1114 183 Average: 182 </code></pre> <p>The C++ code in release mode is almost 3.7 times faster than the assembly code. Why?</p> <p>I guess that the assembly code I wrote is not as effective as those generated by GCC. It's hard for a common programmer like me to wrote code faster than its opponent generated by a compiler.Does that mean I should not trust the performance of assembly language written by my hands, focus on C++ and forget about assembly language?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload