为什么优化前std :: unique_ptr比标准指针慢得多? [英] Why is std::unique_ptr much slower than standard pointer... before optimizations?

查看:197
本文介绍了为什么优化前std :: unique_ptr比标准指针慢得多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Lesson learned, always use optimizations when doing benchmarks...

我决定查看 std :: unique_ptr 作为我程序的替代方法。为什么不重要的原因。

I decided to look at std::unique_ptr as an alternative for my program. The reasons as to why are not important.

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

After using compiler optimizations, they seems to take equivalent amounts of time.

我如何测试:

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: %f\n", duration);

我的环境:


  • Windows 8.1 64位

  • MSVC编译器。使用发行版。

  • 英特尔4790k(标准时钟)

  • 1600 MHz RAM

  • Windows 8.1 64 bit
  • MSVC compiler in Visual Studio 2013. Using Release.
  • Intel 4790k (standard clock)
  • 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
*/


推荐答案

因为标准编译器标志表示您在未启用优化的情况下进行编译。

Because "standard compiler flags" means you're compiling without optimizations enabled.

std :: unique_ptr 是原始指针的薄包装。这样,在取消引用时,它会通过一个非常简单的转发功能,编译器可以对其进行优化。但是,只有启用优化后,它才会这样做。如果是这样,则可以消除遍历包装程序的开销,因此性能将与使用原始指针相同。

std::unique_ptr is a thin wrapper around a raw pointer. As such, when dereferencing it, it goes through a very simple forwarding function, which the compiler is able to optimize away. But it only does that if optimizations are enabled. If they are, then it can eliminate the overhead of going through the wrapper, so performance will be the same as if you'd just used a raw pointer.

但是如果您不要求编译器优化代码,那么每次访问该指针时,它都必须通过小型包装函数来到达 actual 内部指针。

But if you don't ask the compiler to optimize your code, then every time you access the pointer, it has to go through the small wrapper function to get to the actual internal pointer.

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

Always, always enable optimization when benchmarking code.

这篇关于为什么优化前std :: unique_ptr比标准指针慢得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆