memcpy和memmove的意外性能

时间:2013-08-11 21:27:15

标签: c performance memory-management

为什么memcpy在我的系统上执行速度比memmove慢?

通过阅读其他SO问题,例如thisthis给人的印象是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;
}

1 个答案:

答案 0 :(得分:1)

正如@Carl Norum和@Greg Hewgill所说:缓存效应。

您肯定会遇到缓存内存的影响。重新排序测试并比较结果。当我在memcpy()之前和之后测试memmove()时,第二个memcpy()的效果与memove()相同,并且比第一个memcpy()更快。