整型memcpy與直接指針取值

網絡編程常常要作字節序轉換,避免不了整型拷貝
是直接用指針類型轉換,仍是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<s; i++)
    {
        uint64_t tmp = *(uint64_t*)buf;
        if(tmp != -1)
        {
            printf("MemTestFail \n");
        }
    }
    uint64_t t2 = GetNanoTick();
    for(int i=0; i<s; i++)
    {
        uint64_t tmp;
        memcpy(&tmp, buf, sizeof tmp);
        if(tmp != -1)
        {
            printf("MemTestFail \n");
        }
    }
    uint64_t t3 = GetNanoTick();
    for(int i=0; i<s; i++)
    {
        uint64_t tmp = *(uint64_t*)bufx;
        if(tmp != -1)
        {
            printf("MemsetTestFail \n");
        }
    }
    uint64_t t4 = GetNanoTick();
    for(int i=0; i<s; 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結果
clipboard.png
debug結果
clipboard.png網絡

相關文章
相關標籤/搜索