Mic*_*ell 0 c++ performance pointers unique-ptr c++11
经验教训,在做基准测试时总是使用优化...
我决定将其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: %f\n", duration);
Run Code Online (Sandbox Code Playgroud)
我的环境:
我的结果(使用优化编译):
// 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
*/
Run Code Online (Sandbox Code Playgroud)
jal*_*alf 14
因为"标准编译器标志"意味着您正在编译而未启用优化.
std::unique_ptr是一个原始指针周围的薄包装器.因此,当解除引用它时,它会通过一个非常简单的转发函数,编译器可以将其优化掉.但只有在启用优化的情况下才会这样做.如果它们是,那么它可以消除通过包装器的开销,因此性能将与您刚刚使用原始指针一样.
但是如果你不要求编译器优化你的代码,那么每次你访问指针时,都必须通过小包装器函数来获取实际的内部指针.
在对代码进行基准测试时始终始终启用优化.