![](/img/trans.png)
[英]Given a tuple with arbitrary number of vectors holding different types how do I extract the vector with minimum size?
[英]The cost of forking threads: How do I determine the minimum vector size to justify multithreading
我正在尝试计算许多矢量对的点积。 每个点积可以使用多个线程,但是由于数据依赖性,不应同时执行两个或多个点积。 这里可以证明多线程合理的最小向量大小是多少? 我意识到没有人能够给我确切的答案,所以我只是在寻找粗略的估计。
为问题添加更多的上下文:我的程序需要计算很多点积,但是一次只能完成一个点积。
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);
}
我的经验是线程非常繁重。 编写它,以便您可以将可变大小的工作块传递给线程。 然后,您可以根据需要进行调整。
我还将考虑使用可以使用线程或GPU的库。 我敢打赌,GPU在做点积方面将非常出色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.