簡體   English   中英

memcpy和memmove的意外性能

[英]Unexpected performance from memcpy and memmove

為什么memcpy在我的系統上執行速度比memmove慢?

通過閱讀其他SO問題,比如這個或者這個問題給人的印象是memcpy應該比memmove更快,直觀地說,這應該是這樣。 畢竟,memcpy的檢查次數較少,手冊頁也與他們所說的相符。

但是,當測量每個函數內部所花費的時間時,memmove會記住memcpy! 更重要的是,它似乎也超過了memset,當memset似乎可以從memcpy或memmove無法實現的優化中受益。 為什么會這樣?

我的電腦上的結果(眾多之一):

[INFO] (ex23.c:151 func: main) Normal copy: 109092
[INFO] (ex23.c:198 func: main) memcpy: 66070
[INFO] (ex23.c:209 func: main) memmove: 53149
[INFO] (ex23.c:219 func: main) memset: 52451

用於給出此結果的代碼:

#include <stdio.h>
#include <string.h>
#include "dbg.h" // debugging macros
#include <time.h>

int main(int argc, char *argv[])
{
    char from[10000] = {'a'};
    char to[10000] = {'c'};
    int rc = 0;
    struct timespec before; 
    memset(from, 'x', 10000);
    memset(to, 'y', 10000);

    clock_gettime(CLOCK_REALTIME, &before);

    // naive assignment using a for loop
    normal_copy(from, to, 10000);
    struct timespec after;
    clock_gettime(CLOCK_REALTIME, &after);
    log_info("Normal copy: %ld", (after.tv_nsec - before.tv_nsec));


    memset(to, 'y', 10000);
    clock_gettime(CLOCK_REALTIME, &before); 
    memcpy(to, from, 10000);
    clock_gettime(CLOCK_REALTIME, &after);
    log_info("memcpy: %ld", (after.tv_nsec - before.tv_nsec));

    memset(to, 'y', 10000);
    clock_gettime(CLOCK_REALTIME, &before);
    memmove(to, from, 10000);
    clock_gettime(CLOCK_REALTIME, &after);
    log_info("memmove: %ld", (after.tv_nsec - before.tv_nsec));

    memset(to, 'y', 10000);
    clock_gettime(CLOCK_REALTIME, &before);
    memset(to, 'x', 10000);
    clock_gettime(CLOCK_REALTIME, &after);
    log_info("memset: %ld", (after.tv_nsec - before.tv_nsec));

    return 0;
}

正如@Carl Norum和@Greg Hewgill所說:緩存效果。

你當然會體驗到緩存內存的影響。 重新排序測試並比較結果。 當我在memmove() memcpy()之前和之后測試memcpy() ,第二個memcpy()表現得像memove()並且比第一個memcpy()更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM