【测速】memcpy()对比for循环逐个对象拷贝

[color=red][size=x-large]结论:[/size][/color][size=large]一般情况下,memcpy()函数比for循环快个一两倍,某些特殊值上稍微慢点儿。[/size]

[color=red][size=x-large]注意:[/size][/color][size=large]对于需要构造函数、析构函数的类,可能要在拷贝时重载=运算符,此时memcpy()的结果就不是自己想要的了,一般情况下还是老老实实用for循环吧[/size]

[color=red][size=x-large]测试结果如下:[/size][/color]

[img]http://dl.iteye.com/upload/attachment/0076/7247/72a8b802-9e0f-3250-865f-1382aeb40acb.png[/img]

[img]http://dl.iteye.com/upload/attachment/0076/7249/56277b42-e09e-3428-aaa4-7c1134982201.png[/img]

[img]http://dl.iteye.com/upload/attachment/0076/7251/e7eb916a-c74c-3dbd-ad80-27a3267bf17c.png[/img]

[img]http://dl.iteye.com/upload/attachment/0076/7253/7d40e60c-b2f0-31cc-9321-15c2bf2ce0b4.png[/img]

[color=red][size=x-large]测试代码如下(不完全):[/size][/color]
#include 
#include "..\Include\lc\utility\Timer.hpp"
#include

using namespace LC;
void main() {
typedef long long worktype;
//typedef int worktype;

for(int num=10; num<10000000; num*=5) {
const int testNum=10000000/num*100;
worktype* pDst=new worktype[num];
worktype* pSrc=new worktype[num];

Timer timer;
for (int i=0; i memcpy(pDst,pSrc,sizeof(worktype) * num );
}
long tMemcpy=timer.getElapsedTimeAndRestart();

for (int i=0; i for (int n=0; n pDst[n]=pSrc[n];
}
}
long timeCopy=timer.getElapsedTimeAndRestart();

std::cout<<"数组长度:"< }
}

你可能感兴趣的:(C++)