gpt4 book ai didi

multithreading - 多线程,为什么此串行代码比其并行版本要快?

转载 作者:行者123 更新时间:2023-12-03 13:15:12 27 4
gpt4 key购买 nike

我正在尝试使用cpp11中的一些多线程,但无法弄清楚为什么在以下代码中,串行版本比并行版本快得多。

我知道在这个最小的示例中,不应该对计算功能进行并行化,但是我想在RayTracing算法中使用类似的方法对像素渲染进行并行化,在这种算法中,计算所需的时间要长得多,但是在在其他情况下的持续时间。

我想我缺少有关线程的信息。任何帮助或指导将不胜感激。

#include <iostream>
#include <thread>
#include <vector>
#include <chrono>

void compute(double& res)
{
res = 2*res;
}

void computeSerial(std::vector<double>& res, const size_t& nPoints)
{
for (size_t i = 0; i < nPoints; i++)
{
compute(res[i]);
}
}

void computeParallel(std::vector<double>& res, const size_t& nPoints)
{
int numThreads = std::thread::hardware_concurrency() - 1;
std::vector<std::thread*> pool(numThreads, nullptr);
size_t nPointsComputed = 0;
while(nPointsComputed < nPoints)
{
size_t firstIndex = nPointsComputed;
for (size_t i = 0; i < numThreads; i++)
{
size_t index = firstIndex + i;
if(index < nPoints)
{
pool[i] = new std::thread(compute, std::ref(res[index]));
}
}
for (size_t i = 0; i < numThreads; i++)
{
size_t index = firstIndex + i;
if(index < nPoints)
{
pool[i]->join();
delete pool[i];
}
}
nPointsComputed += numThreads;
}
}

int main(void)
{
size_t pbSize = 1000;
std::vector<double> vSerial(pbSize, 0);
std::vector<double> vParallel(pbSize, 0);
for (size_t i = 0; i < pbSize; i++)
{
vSerial[i] = i;
vParallel[i] = i;
}

int numThreads = std::thread::hardware_concurrency();
std::cout << "Number of threads: " << numThreads << std::endl;

std::chrono::steady_clock::time_point begin, end;

begin = std::chrono::steady_clock::now();
computeSerial(vSerial, pbSize);
end = std::chrono::steady_clock::now();
std::cout << "duration serial = " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count() << "[ns]" << std::endl;

begin = std::chrono::steady_clock::now();
computeParallel(vParallel, pbSize);
end = std::chrono::steady_clock::now();
std::cout << "duration parallel = " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count() << "[ns]" << std::endl;

return 0;
}

clang++ -pthread main.cc编译后,我得到以下输出:
Number of threads: 6
duration serial = 23561[µs]
duration parallel = 12219928[µs]

无论计算的 double 数是多少,串行版本始终比并行版本快得多。

最佳答案

启动线程(甚至只是进行动态分配)需要更多的指令来计算数字的两倍。

您需要将工作分成更大的块...启动一个单独的CPU线程只是为了计算2*x,这绝不是一项优化。

将4000000个数字的两倍的计算工作拆分为4个线程可能是有意义的,每个线程在循环中计算1000000个结果。

GPU的情况大不相同,例如可以为每个像素运行一个线程。

关于multithreading - 多线程,为什么此串行代码比其并行版本要快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60588526/

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