【发布时间】:2020-05-14 23:14:21
【问题描述】:
当使用g++ 标志-O3 编译时,这些函数对数组和向量求和似乎存在性能差异:
float sum1(float* v, int length) {
float sum = 0;
for(int i = 0; i < length; i++) {
sum += v[i];
}
return sum;
}
float sum2(std::vector<float> v) {
return sum1(&v[0], v.size());
}
当调用 sum1 时,例如一个长度为 100000 和 sum2 的向量具有相同的长度和内容,sum2 最终约为。在我的测试中比 sum1 慢 10%。
测量的运行时间是:
sum1: 0.279816 ms
sum2: 0.307811 ms
现在这个开销是从哪里来的?附加您还可以找到我在那里犯错的可能性的完整测试代码。
[更新] 当通过引用 (float sum2(std::vector<float>& v)) 调用时,性能差异约为还剩 3.7%,所以这有帮助,但其他地方仍然有一些性能损失?
[Update2] 其余部分似乎在统计上占主导地位,如更多迭代所示。因此,唯一的问题是通过引用调用!
完整的测试代码(用g++标记-O3编译,也用clang++测试):
#include <iostream>
#include <chrono>
#include <vector>
using namespace std;
std::vector<float> fill_vector(int length) {
std::vector<float> ret;
for(int i = 0; i < length; i++) {
float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
ret.push_back(r);
}
return ret;
}
float sum1(float* v, int length) {
float sum = 0;
for(int i = 0; i < length; i++) {
sum += v[i];
}
return sum;
}
float sum2(std::vector<float> v) {
return sum1(&v[0], v.size());
}
int main() {
int iterations = 10000;
int vector_size = 100000;
srand(42);
std::vector<float> v1 = fill_vector(vector_size);
float* v2;
v2 = &v1[0];
std::chrono::duration<double, std::milli> duration_sum1(0);
for(int i = 0; i < iterations; i++) {
auto t1 = std::chrono::high_resolution_clock::now();
float res = sum1(v2, vector_size);
auto t2 = std::chrono::high_resolution_clock::now();
cout << "Result sum1: " << res << endl;
duration_sum1 += t2 - t1;
}
duration_sum1 /= iterations;
std::chrono::duration<double, std::milli> duration_sum2(0);
for(int i = 0; i < iterations; i++) {
auto t1 = std::chrono::high_resolution_clock::now();
float res = sum2(v1);
auto t2 = std::chrono::high_resolution_clock::now();
cout << "Result sum2: " << res << endl;
duration_sum2 += t2 - t1;
}
duration_sum2 /= iterations;
cout << "Durations:" << endl;
cout << "sum1: " << duration_sum1.count() << " ms" << endl;
cout << "sum2: " << duration_sum2.count() << " ms" << endl;
}
【问题讨论】:
-
尝试改变测试的顺序...在 sum1 之前调用 sum2
-
尝试更改
float sum2(std::vector<float>& v)。 -
@2xB
float sum2(std::vector<float> v)-- C++ 有多种传递参数的方式。不幸的是,您选择了“按价值”,而不是“按参考”。 -
@PetokLorand 按值传递调用向量的深层副本。
-
除此之外:更喜欢
v.data()而不是&v[0]。还有float sum3(std::vector<float> & v) { return std::accumulate(v.begin(), v.end(), 0.0f); }
标签: c++ arrays performance vector stdvector