【发布时间】:2019-01-15 16:19:39
【问题描述】:
我试图理解为什么在以下示例中运行在单线程上的 std::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(表中用红色提到)并且我的代码正在并行运行!?
【问题讨论】:
-
请注意,
<parallel/algorithm>不是 C++17 的官方并行库。它在文件中说:“这个文件是标准 C++ 库的 GNU 扩展”。 -
你能显示使用
__gnu_parallel::for_each的代码吗? -
std::foreach可能正在使用 SIMD 指令优化为一个简单的循环 -
循环也可能太短以至于并行性没有任何用处。创建线程并加入它们是有成本的。
-
@NathanOliver 完全一样,只需将“std::”替换为“__gnu_parallel::”这就是我每次都更改的内容
标签: c++ parallel-processing stl