为什么std::unique_ptr比标准指针慢得多..在优化之前

Why is std::unique_ptr much slower than standard pointer... before optimizations?

本文关键字:优化 标准 unique std ptr 为什么 指针      更新时间:2023-10-16

经验教训,在进行基准测试时始终使用优化。。。


我决定将std::unique_ptr作为我的程序的替代方案。原因并不重要。

在使用编译器优化之后,它们似乎花费了相当多的时间。

我的测试方式:

time_t current_time;
time(&current_time);
srand((int)current_time);
//int* p0 = new int[NUM_TESTS];
//int* p1 = new int[NUM_TESTS];
std::unique_ptr<int[]> u_p0{ new int[NUM_TESTS] };
std::unique_ptr<int[]> u_p1{ new int[NUM_TESTS] };
for (unsigned i = 0; i < NUM_TESTS; ++i){
    u_p0[i] = rand(); // Use p0 and p1 for the standard ptr test
    u_p1[i] = rand();
}
int result;
auto start = std::chrono::steady_clock::now();
for (unsigned index = 0; index < NUM_TESTS; ++index){
    result = u_p0[index] + u_p1[index]; // Use p0 and p1 for standard ptr test
}
auto end = std::chrono::steady_clock::now();
double duration = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();
printf("time: %fn", duration);

我的环境:

  • Windows 8.1 64位
  • Visual中的MSVC编译器;工作室;2013.使用Release
  • Intel 4790k(标准时钟)
  • 1600 MHz RAM

我的结果(使用优化编译):

// NUM_TESTS = 1,000,000
/*
STD:
    0.001005
    0.001001
    0.001000
    0.001000
    0.001015
*/
/*
unique_ptr:
    0.001000
    0.001000
    0.000997
    0.001000
    0.001017
*/

因为"标准编译器标志"意味着您在编译时没有启用优化。

std::unique_ptr是一个围绕原始指针的精简包装器。因此,当取消引用它时,它会通过一个非常简单的转发函数,编译器可以对其进行优化。但只有在启用了优化的情况下,它才能做到这一点。如果是,那么它可以消除通过包装器的开销,因此性能将与您刚刚使用的原始指针相同。

但是,如果你不要求编译器优化你的代码,那么每次访问指针时,它都必须通过小包装器函数才能到达实际的内部指针。

始终,始终在基准测试代码时启用优化。