比较memcpy()内存拷贝和"="赋值操作效率,测试代码如下
#include <stdio.h>
#include <malloc.h>
#include <windows.h>
#define QueryFreAndCounter(m_fre,tt) QueryPerformanceFrequency(&m_fre);\
QueryPerformanceCounter(&tt);
#define Timecost(t2,t1,fre,tt1)\
QueryPerformanceCounter(&t2);\
tt1=(double)1000.0*(t2.QuadPart - t1.QuadPart) / fre.QuadPart;
using namespace std;
int main()
{
double TimeCost = 0;
LARGE_INTEGER m_frequency = { 0 }, m_time1 = { 0 }, m_time2 = { 0 };
int t = 10000,t1=10000;
int n = 10;
int a[10] = { 1 };
int b[10];
QueryFreAndCounter(m_frequency, m_time1);
while (t)
{
memcpy(b, a, n);
--t;
}
Timecost(m_time2, m_time1, m_frequency, TimeCost);
printf("memcpy cost %.3f ms\n", TimeCost);
QueryFreAndCounter(m_frequency, m_time1);
while (t1)
{
for (int i = 0; i < n; ++i)
{
b[i] = a[i];
}
--t1;
}
Timecost(m_time2, m_time1, m_frequency, TimeCost);
printf("assignment cost %.3f ms\n", TimeCost);
system("pause");
}
运行结果:
debug下
release下
总结,以上数据量比较大的情况下,memcpy效率>赋值操作,同时本人也测了数据量比较下的情况memcpy效率也很高,和赋值操作差不多。