- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我试图理解为什么在单线程上运行的 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/
这让我很困惑,如果有人能帮助我,我将不胜感激。 (编辑:以为这是一个模板化问题,我误会了) 我想使用 gnu 的并行累积算法(存储在 #include 中)添加以下类的多个拷贝 类故意不做太多,我觉
在我的代码中的某个时刻,我必须对 unordered_map 中的所有元素进行操作。为了加速这个过程,我想使用 openMP,但是天真的方法不起作用: std::unordered_map hastT
在我的代码中的某个时刻,我必须对 unordered_map 中的所有元素进行操作。为了加速这个过程,我想使用 openMP,但是天真的方法不起作用: std::unordered_map hastT
我试图理解为什么在单线程上运行的 std::for_each 比 __gnu_parallel::for_each 快 ~3 倍在下面的示例中: Time =0.478101 milliseconds
我是一名优秀的程序员,十分优秀!