[C++] 内嵌汇编和调用汇编函数

内嵌汇编

在VS中可以加入__asm来内在VS中的测试。

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
  clock_t start, end;
  int Sum=0,Count=100000000;
  int Block = 20000000;
  start = clock();

  __asm 
  {
    MOV ECX, Count
  L1: PUSH ECX
    MOV EAX, 1
    MOV ECX, 20
  L2: SHL EAX, 1
    INC Sum
    LOOP L2
    POP  ECX
    LOOP L1
  }
  
  cout << Sum << endl;
  end = clock();
  cout << ((double)end - (double)start) / CLOCKS_PER_SEC << endl;
  
  start = clock();
  Sum = 0;
  for (int i = 0; i < Count; i++)
  {
    int Ax = 1;
    for (int j = 0; j < 20; j++)
    {
      Ax = Ax << 1;
      Sum++;
    }
  }
  cout << Sum << endl;
  end = clock();
  cout << ((double)end - (double)start) / CLOCKS_PER_SEC << endl;
  return 0;
}

但貌似还是C++源码快(逃。可能是现代编译器太强了。

C++调用汇编函数

TITLE AsmFindArray Procedure
.586
.model flat,C

AsmFindArray PROTO,
  Val:DWORD,Array:PTR DWORD,N:DWORD
.code
AsmFindArray PROC USES edi,
  Val:DWORD,Array:PTR DWORD,N:DWORD
  true=1
  false=0

  mov		eax,Val
  mov		ecx,N
  mov		edi,Array

  repne	scasd
  jz		rT
rF:
  mov		al,false
  jmp		short exit
rT:
  mov		al,true
exit:
  ret
AsmFindArray	ENDP
END
#include <iostream>
#include <ctime>
using namespace std;

extern "C" bool AsmFindArray(int Val, int Array[], int N);
bool FindArray(int Val, int Array[], int N)
{
  for (int i = 0; i < N; i++)
    if (Array[i] == Val)
      return true;
  return false;
}
int Num = 100000;
int A[100010];
int main()
{
  for (int i = 0; i < Num; i++)
    A[i] = i;
  int Sum = 0;

  clock_t start, end;

  start = clock();
  for (int i = 0; i <= Num * 2; i++)
    Sum += AsmFindArray(i, A, Num);
  end = clock();
  cout << Sum << endl;
  cout << "ASM:" << ((double)end - (double)start) / CLOCKS_PER_SEC << endl;

  Sum = 0;
  start = clock();
  for (int i = 0; i <= Num * 2; i++)
    Sum += FindArray(i, A, Num);
  end = clock();
  cout << Sum << endl;
  cout << "C++:" << ((double)end - (double)start) / CLOCKS_PER_SEC << endl;
  return 0;
}

VS中汇编的调用需要一些设定,用的时候可以百度一下,结果的优化还是挺明显的。

不过还是比不过开了O2优化的代码。
所以感觉一般汇编优化还是在一些不能开O优化的场合用比较好。

参考文献:Intel汇编程序设计