gpt4 book ai didi

c++ - OpenMP 与 C++11 线程

转载 作者:IT老高 更新时间:2023-10-28 22:02:48 26 4
gpt4 key购买 nike

在以下示例中,C++11 线程的执行时间约为 50 秒,而 OMP 线程只需 5 秒。任何想法为什么? (我可以向你保证,如果你正在做真正的工作而不是 doNothing,或者如果你以不同的顺序来做,等等。)我也在 16 核机器上。

#include <iostream>
#include <omp.h>
#include <chrono>
#include <vector>
#include <thread>

using namespace std;

void doNothing() {}

int run(int algorithmToRun)
{
auto startTime = std::chrono::system_clock::now();

for(int j=1; j<100000; ++j)
{
if(algorithmToRun == 1)
{
vector<thread> threads;
for(int i=0; i<16; i++)
{
threads.push_back(thread(doNothing));
}
for(auto& thread : threads) thread.join();
}
else if(algorithmToRun == 2)
{
#pragma omp parallel for num_threads(16)
for(unsigned i=0; i<16; i++)
{
doNothing();
}
}
}

auto endTime = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = endTime - startTime;

return elapsed_seconds.count();
}

int main()
{
int cppt = run(1);
int ompt = run(2);

cout<<cppt<<endl;
cout<<ompt<<endl;

return 0;
}

最佳答案

OpenMP thread-pools for its Pragmas (还有 herehere )。启动和拆除线程是昂贵的。 OpenMP 避免了这种开销,因此它所做的只是实际工作和执行状态的最小共享内存穿梭。在您的 Threads 代码中,您每次迭代都会启动并拆除一组新的 16 个线程。

关于c++ - OpenMP 与 C++11 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23258037/

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