我想对n
×d
维数组应用非常简单的直接计算。目的是使用pthreads
将顺序计算转换为并行计算。我的问题是:拆分问题的最佳方法是什么?>? 如何大大减少脚本的执行时间?我提供了一个用C语言编写的顺序代码示例,以及一些我已经尝试过的并行实现的想法。
double * calcDistance(double * X ,int n, int d) { //calculate and return an array[n-1] of all the distances //from the last point double *distances = calloc(n,sizeof(double)); for(int i=0 ; i<n-1; i++) { //distances[i]=0; for (int j=0; j< d; j++) { distances[i] += pow(X[(j+1)*n-1]-X[j*n+i], 2); } distances[i] = sqrt(distances[i]); } return distances; }
我提供了
main()
调用程序功能,以便使样本完整且可测试:
#include <stdio.h>
#include <stdlib.h>
#define N 10 //00000
#define D 2
int main()
{
srand(time(NULL));
//allocate the proper space for X
double *X = malloc(D*N*(sizeof(double)));
//fill X with numbers in space (0,1)
for(int i = 0 ; i<N ; i++)
{
for(int j=0; j<D; j++)
{
X[i+j*N] = (double) (rand() / (RAND_MAX + 2.0));
}
}
X = calcDistances(X, N, D);
return 0;
}
pthreads
的global_index
和mutex
异步使用local_index
。通过使用while()
循环,在每次迭代中将local_index
分配给每个线程。 local_index
分配取决于当时的global_index
值(均发生在mutual exclusion
块中)。线程在distances[local_index]
元素上执行计算。不幸的是,与上面引用的顺序执行相比,这种实现导致程序慢得多,执行时间增加了10倍或20倍。 pthread
。我不知道这是否是一种通用的程序。我想对n维维数组应用非常简单的直接计算。目标是使用pthread将顺序计算转换为并行计算。我的问题是:...
您的内部循环会跨步跨越数组X
,其步幅随外循环迭代。除非n
和d
很小,否则[*]可能会产生不良的缓存使用率-在串行代码中也是如此,但是并行化会放大这种效果。该函数未写入至少X
,从而改善了外观。另外,在外部循环的迭代之间似乎没有任何数据依赖性,这很好。