memcpy 和直接赋值的性能差异
不废话,看代码:
#include <time.h>
#include <stdint.h>
#include <iostream>
#define ARR_LEN 10
#define CAL_TIMES 100000000
int64_t a[ARR_LEN];
int64_t b[ARR_LEN];
int main() {
for (size_t i(0); i < ARR_LEN; ++ i) a[i] = i;
clock_t s1 = clock();
for (size_t i(0); i < CAL_TIMES; ++ i) {
for (size_t j(0); j < ARR_LEN; ++ j) {
b[j] = a[j];
}
}
double t1 = static_cast<double>(clock() - s1) / CLOCKS_PER_SEC;
memset(b, 0, ARR_LEN);
clock_t s2 = clock();
for (size_t i(0); i < CAL_TIMES; ++ i) {
memcpy(b, a, ARR_LEN * sizeof(a[0]));
}
double t2 = static_cast<double>(clock() - s2) / CLOCKS_PER_SEC;
std::cout << "t1 = " << t1 << "\nt2 = " << t2 << std::endl;
return 0;
}
编译并运行:
$ g++ a.cpp -o a
$ ./a
t1 = 2.79
t2 = 0.5