分析显示:std::copy()总是和memcpy()一样快或更快为false。
我的系统:
HP-Compaq-dx7500-Microtower 3.13.0-24-generic #47-Ubuntu SMP周五5月2日
23:30:00 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux。
gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2
代码(语言:c++):
const uint32_t arr_size = (1080 * 720 * 3); //HD image in rgb24
const uint32_t iterations = 100000;
uint8_t arr1[arr_size];
uint8_t arr2[arr_size];
std::vector<uint8_t> v;
main(){
{
DPROFILE;
memcpy(arr1, arr2, sizeof(arr1));
printf("memcpy()\n");
}
v.reserve(sizeof(arr1));
{
DPROFILE;
std::copy(arr1, arr1 + sizeof(arr1), v.begin());
printf("std::copy()\n");
}
{
time_t t = time(NULL);
for(uint32_t i = 0; i < iterations; ++i)
memcpy(arr1, arr2, sizeof(arr1));
printf("memcpy() elapsed %d s\n", time(NULL) - t);
}
{
time_t t = time(NULL);
for(uint32_t i = 0; i < iterations; ++i)
std::copy(arr1, arr1 + sizeof(arr1), v.begin());
printf("std::copy() elapsed %d s\n", time(NULL) - t);
}
}
g++ -O0 -o test_stdcopy test_stdcopy.cpp
Memcpy()配置文件:main:21: now:1422969084:04859 elapsed:2650 us
Std::copy()配置文件:main:27: now:1422969084:04862 elapsed:2745 us
Memcpy()消失44秒std::copy()消失45秒
g++ -O3 -o test_stdcopy test_stdcopy.cpp
Memcpy()配置文件:主要:21:现在:1422969601:04939经过:2385 us
Std::copy()配置文件:main:28: now:1422969601:04941 elapsed:2690 us
Memcpy()消失了27秒std::copy()消失了43秒
红色警报指出,代码使用memcpy从数组到数组和std::复制从数组到向量。这可能是memcpy更快的原因。
因为有
v .储备(sizeof (arr1);
复制到向量或数组时应该没有区别。
代码在这两种情况下都固定使用数组。Memcpy更快:
{
time_t t = time(NULL);
for(uint32_t i = 0; i < iterations; ++i)
memcpy(arr1, arr2, sizeof(arr1));
printf("memcpy() elapsed %ld s\n", time(NULL) - t);
}
{
time_t t = time(NULL);
for(uint32_t i = 0; i < iterations; ++i)
std::copy(arr1, arr1 + sizeof(arr1), arr2);
printf("std::copy() elapsed %ld s\n", time(NULL) - t);
}
memcpy() elapsed 44 s
std::copy() elapsed 48 s