jjccx

jjccx's blog
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

关于交换两个整数变量的值

Posted on 2005-06-19 23:52  jjccx  阅读(470)  评论(0)    收藏  举报

 

// ASMTest.cpp : 定义控制台应用程序的入口点。

//

 

#include "stdafx.h"

 

int _tmain(int argc, _TCHAR* argv[])

{

 

     int a = 35;

     int b = 4;

     int m;

     register m2;

 

     DWORD t1, t2;

 

     t1 = GetTickCount();

 

     for(int j = 0; j < 1000000001; j++)

     {

         m = a;

         a = b;

         b = m;

     }

 

     t2 = GetTickCount();

 

     printf("Middle Variable:%d\n", t2 - t1);

 

     printf("%d, %d\n", a, b);

 

     t1 = GetTickCount();

 

     for(int j = 0; j < 1000000001; j++)

     {

         m2 = a;

         a = b;

         b = m2;

     }

 

     t2 = GetTickCount();

 

     printf("Register:%d\n", t2 - t1);

 

     printf("%d, %d\n", a, b);

 

     t1 = GetTickCount();

 

     for(int j = 0; j < 1000000001; j++)

     {

         a = a ^ b;

         b = b ^ a;

         a = a ^ b;

     }

 

     t2 = GetTickCount();

 

     printf("Xor Ver 1: %d\n", t2 - t1);

 

     printf("%d, %d\n", a, b);

 

     t1 = GetTickCount();

 

     for(int j = 0; j < 1000000001; j++)

     {

         a ^= b ^= a ^= b;

     }

 

     t2 = GetTickCount();

 

     printf("Xor VER 2: %d\n", t2 - t1);

 

     printf("%d, %d\n", a, b);

 

     t1 = GetTickCount();

 

     for(int j = 0; j < 1000000001; j++)

     {

         __asm

         {

              mov eax, a

              mov ebx, b

              xor eax, ebx

              xor ebx, eax

              xor eax, ebx

              mov a, eax

              mov b, ebx

         }

     }

 

     t2 = GetTickCount();

 

     printf("ASSEMBLE VER 1:%d\n", t2 - t1);

 

     printf("%d, %d\n", a, b);

 

     t1 = GetTickCount();

 

     for(int j = 0; j < 1000000001; j++)

     {

         __asm

         {

              mov eax, a

              mov ebx, b

              mov a, ebx

              mov b, eax

         }

     }

 

     t2 = GetTickCount();

 

     printf("ASSEMBLE VER 2:%d\n", t2 - t1);

 

     printf("%d, %d\n", a, b);

 

 

     return 0;

}

Debug:

Middle Variable:33428
4, 35
Register:30614
35, 4
Xor Ver 1: 65484
4, 35
Xor VER 2: 74036
35, 4
ASSEMBLE VER 1:33018
4, 35
ASSEMBLE VER 2:25687
35, 4
Press any key to continue

Release:

Middle Variable:9324
4, 35
Register:9253
35, 4
Xor Ver 1: 14210
4, 35
Xor VER 2: 14381
35, 4
ASSEMBLE VER 1:31726
4, 35
ASSEMBLE VER 2:14070
35, 4
Press any key to continue

////////////////////////////////////////////////////////////////////////////////////////////

可见:使用中间变量时是最快的,当然,除开在Debug版本下。以前比较喜欢用a ^= b ^= a ^= b来交换两个变量的值,因为这个看起来有点COOL,现在才发觉最简单的最易懂的原来是最好的,呵呵。使用内嵌汇编,Debug版和Release版差别不是很大而其他的方式差别要大得多,我们可以想想其中的原因……呵呵
注:由于本人刚对汇编升起一点兴趣,所以不敢保证上面的内嵌汇编代码是有效率的!