为什么 memcpy 在我的系统上的执行速度比 memmove 慢?
从阅读诸如this或this之类的其他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;
}