gpt4 book ai didi

c++ - fork 线程的成本 : How do I determine the minimum vector size to justify multithreading

转载 作者:行者123 更新时间:2023-11-30 03:06:43 25 4
gpt4 key购买 nike

我正在尝试计算许多 vector 对的点积。每个点积可以使用多个线程,但由于数据依赖,不应同时执行两个或多个点积。这里可以证明多线程的最小 vector 大小是多少?我意识到没有人能够给我一个准确的答案,所以我只是在寻找粗略的估计。

为问题添加更多上下文:我的程序需要计算很多点积,但一次只能计算一个点积。

double serial_dot_product(const double* x, const double* y, size_t length);

我想重写点积使其成为多线程的。但是如果 length 太小,使用多线程就没有任何好处。

编辑。谢谢各位的意见。看起来答案取决于太多因素 - 编译器、CPU、内存、线程库等。

最佳答案

唯一真正了解的方法是尝试一下(请记住,结果可能会因您运行的硬件而异)。您可以编写一个分析例程来自动执行测试,并且(如果您发现这样做值得的话)甚至可以在程序启动时短暂运行该例程,以找出当前硬件的最佳值。

#include <sys/time.h>

unsigned long long GetCurrentTime()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (((unsigned long long)tv.tv_sec)*1000000) + ((unsigned long long)tv.tv_usec);}
}

void FindOptimumMethod()
{
unsigned long long lowestTime = ((unsigned long long)-1);
int bestVectorLength = 0;
int bestNumThreads = 0;
for (int vectorLen=1; vectorLen<100000; vectorLen++)
{
for (int numThreads=1; numThreads<16; numThreads++)
{
unsigned long long startTime = GetCurrentTime();
DoTheCalculation(numThreads, vectorLen);
unsigned long long elapsedTime = GetCurrentTime()-startTime;
if (elapsedTime < lowestTime)
{
lowestTime = elapsedTime;
bestVectorLength = vectorLen;
bestNumThreads = numThreads;
}
}
}
printf("The fastest way is %i threads using a vector length of %i\n", bestNumThreads, bestVectorLength);
}

关于c++ - fork 线程的成本 : How do I determine the minimum vector size to justify multithreading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6359649/

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