我一直在使用 memcmp 函数在我的性能关键应用程序中比较 2 个整数。我不得不使用它而不是使用相等的运算符,因为我必须一般地处理其他数据类型。但是,我怀疑原始数据类型的 memcpy 性能并将其更改为等于运算符。但是,性能有所提高。
我只是做了一些简单的测试,如下所示。
使用 memcmp
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
int main(int argc, char **argv)
{
int iValue1 = atoi(argv[1]);
int iValue2 = atoi(argv[2]);
struct timeval start;
gettimeofday(&start, NULL);
for (int i = 0; i < 2000000000; i++)
{
// if (iValue1 == iValue2)
if (memcmp(&iValue1, &iValue2, sizeof(int)) == 0)
{
cout << "Hello" << endl;
};
};
struct timeval end;
gettimeofday(&end, NULL);
cout << "Time taken : " << ((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)) << " us" << endl;
return 0;
}
该程序的输出如下。
sujith@linux-1xs7:~> g++ -m64 -O3 Main.cpp
sujith@linux-1xs7:~> ./a.out 3424 234
Time taken : 13539618 us
sujith@linux-1xs7:~> ./a.out 3424 234
Time taken : 13534932 us
sujith@linux-1xs7:~> ./a.out 3424 234
Time taken : 13599818 us
sujith@linux-1xs7:~> ./a.out 3424 234
Time taken : 13639394 us
使用相等运算符
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
int main(int argc, char **argv)
{
int iValue1 = atoi(argv[1]);
int iValue2 = atoi(argv[2]);
struct timeval start;
gettimeofday(&start, NULL);
for (int i = 0; i < 2000000000; i++)
{
if (iValue1 == iValue2)
// if (memcmp(&iValue1, &iValue2, sizeof(int)) == 0)
{
cout << "Hello" << endl;
};
};
struct timeval end;
gettimeofday(&end, NULL);
cout << "Time taken : " << ((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)) << " us" << endl;
return 0;
}
该程序的输出如下。
sujith@linux-1xs7:~> g++ -m64 -O3 Main.cpp
sujith@linux-1xs7:~> ./a.out 234 23423
Time taken : 9 us
sujith@linux-1xs7:~> ./a.out 234 23423
Time taken : 13 us
sujith@linux-1xs7:~> ./a.out 234 23423
Time taken : 14 us
sujith@linux-1xs7:~> ./a.out 234 23423
Time taken : 15 us
sujith@linux-1xs7:~> ./a.out 234 23423
Time taken : 16 us
有人可以让我知道对于原始数据类型,等号运算符是否比 memcmp 更快?如果是这样,那里发生了什么?等号运算符不是在里面使用 memcmp 吗?