gpt4 book ai didi

c++ - 为什么 std::for_each 比 __gnu_parallel::for_each 快

转载 作者:太空宇宙 更新时间:2023-11-04 15:57:15 25 4
gpt4 key购买 nike

我试图理解为什么在单线程上运行的 std::for_each__gnu_parallel::for_each~3 倍在下面的示例中:

Time =0.478101 milliseconds

对比

Time =0.166421 milliseconds

这里是我用来进行基准测试的代码:

#include <iostream>
#include <chrono>
#include <parallel/algorithm>

//The struct I'm using for timming
struct TimerAvrg
{
std::vector<double> times;
size_t curr=0,n;
std::chrono::high_resolution_clock::time_point begin,end;
TimerAvrg(int _n=30)
{
n=_n;
times.reserve(n);
}

inline void start()
{
begin= std::chrono::high_resolution_clock::now();
}

inline void stop()
{
end= std::chrono::high_resolution_clock::now();
double duration=double(std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count())*1e-6;
if ( times.size()<n)
times.push_back(duration);
else{
times[curr]=duration;
curr++;
if (curr>=times.size()) curr=0;}
}

double getAvrg()
{
double sum=0;
for(auto t:times)
sum+=t;
return sum/double(times.size());
}
};



int main( int argc, char** argv )
{
float sum=0;
for(int alpha = 0; alpha <5000; alpha++)
{
TimerAvrg Fps;
Fps.start();
std::vector<float> v(1000000);
std::for_each(v.begin(), v.end(),[](auto v){ v=0;});
Fps.stop();
sum = sum + Fps.getAvrg()*1000;
}

std::cout << "\rTime =" << sum/5000<< " milliseconds" << std::endl;
return 0;
}

这是我的配置:

gcc version 7.3.0 (Ubuntu 7.3.0-21ubuntu1~16.04) 

Intel® Core™ i7-7600U CPU @ 2.80GHz × 4

htop 检查程序是在单线程还是多线程中运行

g++ -std=c++17 -fomit-frame-pointer -Ofast -march=native -ffast-math -mmmx -msse -msse2 -msse3 -DNDEBUG -Wall -fopenmp benchmark.cpp -o benchmark 

gcc 8.1.0 无法编译相同的代码。我收到了错误信息:

/usr/include/c++/8/tr1/cmath:1163:20: error: ‘__gnu_cxx::conf_hypergf’ has not been declared
using __gnu_cxx::conf_hypergf;

我已经检查了几个帖子,但要么它们太旧了,要么不是同一个问题..

我的问题是:

为什么并行比较慢?

我使用了错误的功能?

cppreference它是说不支持带有 Standardization of Parallelism TS 的 gcc(在表中用红色提到)并且我的代码正在并行运行!?

最佳答案

您的函数 [](auto v){ v=0;} 非常简单。

该函数可能会被替换为对 memset 的单个调用或使用 SIMD 指令实现单线程并行。知道它会覆盖与 vector 最初具有的相同状态,就可以优化整个循环。优化器替换 std::for_each 可能比并行实现更容易。

此外,假设并行循环使用线程,必须记住创建和最终同步(在这种情况下在处理过程中不需要同步)会产生开销,这对于您的琐碎操作来说可能很重要。

线程并行通常只适用于计算量大的任务。 v=0 是计算成本最低的操作之一。

关于c++ - 为什么 std::for_each 比 __gnu_parallel::for_each 快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54202841/

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