为什么std::unique_ptr比标准指针慢得多..在优化之前
Why is std::unique_ptr much slower than standard pointer... before optimizations?
经验教训,在进行基准测试时始终使用优化。。。
我决定将std::unique_ptr
作为我的程序的替代方案。原因并不重要。
在使用编译器优化之后,它们似乎花费了相当多的时间。
我的测试方式:
time_t current_time;
time(¤t_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
是一个围绕原始指针的精简包装器。因此,当取消引用它时,它会通过一个非常简单的转发函数,编译器可以对其进行优化。但只有在启用了优化的情况下,它才能做到这一点。如果是,那么它可以消除通过包装器的开销,因此性能将与您刚刚使用的原始指针相同。
但是,如果你不要求编译器优化你的代码,那么每次访问指针时,它都必须通过小包装器函数才能到达实际的内部指针。
始终,始终在基准测试代码时启用优化。
相关文章:
- 空基优化子对象的地址
- 使用CMake检测支持的C++标准
- 如何理解C++标准N3337中的expr.const.cast子句8
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 编译标准库类型
- 关闭||运算符优化
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 返回值优化:显式移动还是隐式
- 如何优化标准::设置交集算法(C++)
- 优化将标准::uint32_t插入到标准::向量<char>中
- 关于循环变量优化的标准合规行为是什么?
- clang实现char8_t的方式是否存在缺陷,或者标准的某个黑暗角落是否禁止优化?
- 优化标准::位集与noexcept
- C++对间接运算符的标准描述是否保证内存写入不会被优化掉
- 为什么std::unique_ptr比标准指针慢得多..在优化之前
- 空基类优化现在是强制优化吗(至少对于标准布局类)
- 使用for_each标准或提升工具优化循环
- 与c++编码标准相关的过早优化和过早悲观
- C++ 标准输入的 IO 优化和字符串处理