在C/C++中有没有办法在CPU上并行减少数组?我最近了解到,使用openmp是不可能的。任何其他的选择?CPU上的数组并行减少
3
A
回答
7
已添加:请注意,您可以按照here所述的方式使用OpenMP实现“自定义”缩减。
对于C++:与Intel's TBBparallel_reduce
(SO标签:tbb),可以使在复杂的类型,例如数组和结构降低。尽管与OpenMP的裁减条款相比,所需代码的数量可能会大得多。作为一个例子,我们来并行化一个矩阵 - 向量乘法的简单实现:y=Cx
。串行代码由两个循环:
double x[N], y[M], C[N][M];
// assume x and C are initialized, and y consists of zeros
for(int i=0; i<N; ++i)
for(int j=0; j<M; ++j)
y[j] += C[i][j]*x[i];
通常,并行它的循环交换,使外层循环迭代独立处理它们并行:
#pragma omp parallel for
for(int j=0; j<M; ++j)
for(int i=0; i<N; ++i)
y[j] += C[i][j]*x[i];
但是它并不总是好主意。如果M很小并且N很大,则交换循环将不会给出足够的平行性(例如,考虑计算M维空间中N个点的加权centroid,其中C
是点的阵列并且x
是权重)。所以减少一个数组(即一个点)将会有所帮助。下面是如何将其与TBB进行(对不起,代码并没有进行测试,错误是可能的):
struct reduce_body {
double y_[M]; // accumulating vector
double (& C_)[N][M]; // reference to a matrix
double (& x_)[N]; // reference to a vector
reduce_body(double (&C)[N][M], double (&x)[N]) : C_(C), x_(x) {
for (int j=0; j<M; ++j) y_[j] = 0.0; // prepare for accumulation
}
// splitting constructor required by TBB
reduce_body(reduce_body& rb, tbb::split) : C_(rb.C_), x_(rb.x_) {
for (int j=0; j<M; ++j) y_[j] = 0.0;
}
// the main computation method
void operator()(const tbb::blocked_range<int>& r) {
// closely resembles the original serial loop
for (int i=r.begin(); i<r.end(); ++i) // iterates over a subrange in [0,N)
for (int j=0; j<M; ++j)
y_[j] += C_[i][j]*x_[i];
}
// the method to reduce computations accumulated in two bodies
void join(reduce_body& rb) {
for (int j=0; j<M; ++j) y_[j] += rb.y_[j];
}
};
double x[N], y[M], C[N][M];
...
reduce_body body(C, x);
tbb::parallel_reduce(tbb::blocked_range<int>(0,N), body);
for (int j=0; j<M; ++j)
y[j] = body.y_[j]; // copy to the destination array
免责声明:我与TBB无关。
相关问题
- 1. 在cython并行中减少数组
- 2. 在django上减少用户CPU时间
- 3. 减少数组
- 4. OMP并行减少
- 5. Backgroundworker睡眠减少CPU
- 6. thread_cache_size减少CPU和最大连接数?
- 7. 减少行数
- 8. openCL减少,并传递2d数组
- 9. Swift减少元组数组
- 10. 并行化传递减少
- 11. 加速并行减少OpenCL
- 12. 并行化map减少
- 13. 的OpenCL +的OpenGL以减少CPU和GPU
- 14. 如何减少textdb的CPU使用率?
- 15. 减少线程的CPU使用率
- 16. 减少Javascript的CPU使用率
- 17. 如何减少jquery.min.js的CPU时间?
- 18. 减少Bitmap.Save的CPU使用率。
- 19. 并行for循环与减少和操纵数组
- 20. 减少多维数组
- 21. 减少数组长度
- 22. 。数组减少方法
- 23. 减少坐标数组
- 24. 减少多维数组
- 25. Numpy异或减少数组
- 26. 减少数组信息
- 27. 减少元组
- 28. 多线程来减少CPU时间
- 29. 如何减少CPU使用量?
- 30. 使用nice减少CPU处理时间?
你的意思是“除非使用最近的符合标准的Fortran编译器,否则使用OpenMP是不可能的”,是吗? – talonmies 2012-02-22 17:42:09
@talonmies使用C或C++。我刚刚编辑它! – nouveau 2012-02-22 17:49:13
您可以使用前缀sum编写并行简化算法。 http://en.wikipedia.org/wiki/Prefix_sum – perreal 2012-02-22 17:49:30