gpt4 book ai didi

c++ - 为什么 std::inner_product 比原始实现慢?

转载 作者:太空狗 更新时间:2023-10-29 20:02:17 27 4
gpt4 key购买 nike

这是我天真的点积实现:

float simple_dot(int N, float *A, float *B) {
float dot = 0;
for(int i = 0; i < N; ++i) {
dot += A[i] * B[i];
}

return dot;
}

这是使用 C++ 库:

float library_dot(int N, float *A, float *B) {
return std::inner_product(A, A+N, B, 0);
}

我运行了一些基准测试(代码在这里 https://github.com/ijklr/sse ),库版本慢了很多。我的编译器标志是 -Ofast -march=native

最佳答案

你的两个函数不做同样的事情。该算法使用一个累加器,其类型是从初始值推导,在您的情况下 (0) 是 int。将 float 累加到 int 不仅比累加到 float 花费的时间更长,而且会产生不同的结果。

原始循环代码的等价物是使用初始值 0.0f,或等价于 float{}

(请注意,std::accumulate 在这方面非常相似。)

关于c++ - 为什么 std::inner_product 比原始实现慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43079506/

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