gpt4 book ai didi

C++11 元组性能

转载 作者:可可西里 更新时间:2023-11-01 17:37:02 25 4
gpt4 key购买 nike

我正准备通过使用 std::tuple 使我的代码更加通用在很多情况下,包括单个元素。我的意思是例如 tuple<double>而不是 double .但我决定检查这个特定案例的性能。

这是简单的性能基准测试:

#include <tuple>
#include <iostream>

using std::cout;
using std::endl;
using std::get;
using std::tuple;

int main(void)
{

#ifdef TUPLE
using double_t = std::tuple<double>;
#else
using double_t = double;
#endif

constexpr int count = 1e9;
auto array = new double_t[count];

long long sum = 0;
for (int idx = 0; idx < count; ++idx) {
#ifdef TUPLE
sum += get<0>(array[idx]);
#else
sum += array[idx];
#endif
}
delete[] array;
cout << sum << endl; // just "external" side effect for variable sum.
}

并运行结果:

$ g++ -DTUPLE -O2 -std=c++11 test.cpp && time ./a.out
0

real 0m3.347s
user 0m2.839s
sys 0m0.485s

$ g++ -O2 -std=c++11 test.cpp && time ./a.out
0

real 0m2.963s
user 0m2.424s
sys 0m0.519s

我认为 tuple 是严格的静态编译模板,在这种情况下,所有 get<> 函数都只是正常的变量访问。顺便说一句,此测试中的内存分配大小相同。为什么会出现这种执行时间差?

编辑:问题出在 tuple<> 对象的初始化中。为了使测试更准确,必须更改一行:

     constexpr int count = 1e9;
- auto array = new double_t[count];
+ auto array = new double_t[count]();

long long sum = 0;

之后可以观察到类似的结果:

$ g++ -DTUPLE -g -O2 -std=c++11 test.cpp && (for i in $(seq 3); do time ./a.out; done) 2>&1 | grep real
real 0m3.342s
real 0m3.339s
real 0m3.343s

$ g++ -g -O2 -std=c++11 test.cpp && (for i in $(seq 3); do time ./a.out; done) 2>&1 | grep real
real 0m3.349s
real 0m3.339s
real 0m3.334s

最佳答案

元组的所有默认构造值(因此所有内容均为 0) double 不会默认初始化。

在生成的程序集中,以下初始化循环仅在使用元组时出现。否则它们是等价的。

.L2:
movq $0, (%rdx)
addq $8, %rdx
cmpq %rcx, %rdx
jne .L2

关于C++11 元组性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19145901/

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