gpt4 book ai didi

c++ - 为什么 std::unique_ptr 比标准指针慢得多……在优化之前?

转载 作者:太空宇宙 更新时间:2023-11-04 14:38:00 26 4
gpt4 key购买 nike

<分区>

经验教训,在做基准测试时总是使用优化...


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

我的环境:

  • Windows 8.1 64 位
  • Visual Studio 2013 中的 MSVC 编译器。使用 Release。
  • Intel 4790k(标准时钟)
  • 1600 兆赫内存

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

// 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
*/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com