网络编程经常要做字节序转换,避免不了整型拷贝
是直接用指针类型转换,还是memcpy?
实测下来,release下差不多,debug下memcpy效率要差,毕竟是函数调用,release下应该内联了
void MemcpyTest()
{
int s = 10000000;
char buf[1024];
char * bufx = buf +9;
uint64_t x = -1;
memcpy(buf, &x, sizeof x);
memcpy(bufx, &x, sizeof x);
uint64_t t1= GetNanoTick();
for(int i=0; i
{
uint64_t tmp = *(uint64_t*)buf;
if(tmp != -1)
{
printf("MemTestFail \n");
}
}
uint64_t t2 = GetNanoTick();
for(int i=0; i
{
uint64_t tmp;
memcpy(&tmp, buf, sizeof tmp);
if(tmp != -1)
{
printf("MemTestFail \n");
}
}
uint64_t t3 = GetNanoTick();
for(int i=0; i
{
uint64_t tmp = *(uint64_t*)bufx;
if(tmp != -1)
{
printf("MemsetTestFail \n");
}
}
uint64_t t4 = GetNanoTick();
for(int i=0; i
{
uint64_t tmp;
memcpy(&tmp, bufx, sizeof tmp);
if(tmp != -1)
{
printf("MemsetTestFail \n");
}
}
uint64_t t5 = GetNanoTick();
printf("%lld\n%lld\n%lld\n%lld \n", t2-t1, t3-t2, t4-t3, t5-t4);
}
运行环境win10+vs2008
release结果
debug结果