【发布时间】:2021-07-24 15:52:16
【问题描述】:
我想使用 OpenMP 并行一个大循环以提高其效率。这是玩具代码的主要部分:
vector<int> config;
config.resize(indices.size());
omp_set_num_threads(2);
#pragma omp parallel for schedule(static, 5000) firstprivate(config)
for (int i = 0; i < 10000; ++i) { // the outer loop that I would like to parallel
#pragma omp simd
for (int j = 0; j < indices.size(); ++j) { // pick some columns from a big ref_table
config[j] = ref_table[i][indices[j]];
}
int index = GetIndex(config); // do simple computations on the picked values to get the index
#pragma omp atomic
result[index]++;
}
然后我发现如果我使用 2、4 或 8 个线程,我无法提高效率。并行版本的执行时间通常大于顺序版本。外部循环有 10000 次迭代,它们是独立的,所以我希望多个线程并行执行这些迭代。
我猜性能下降的原因可能包括:config 的私有副本?或者,ref_table 的随机访问?或者,昂贵的原子操作?那么性能下降的确切原因是什么?更重要的是,我怎样才能获得更短的执行时间?
【问题讨论】:
-
GetIndex是做什么的?任何显式或隐藏的内存分配(例如使用向量或列表)? -
indices.size() 有多大?
-
"or, random access of ref_table?"多个线程访问同一个内存位置不是问题,只要这些访问是严格只读的。只有至少有一个线程在该位置执行写操作时才会成为问题。 -
我认为,像往常一样,您的代码受内存限制。这意味着您的程序的速度主要取决于内存读/写的速度。请阅读此答案,我认为它也可能适用于您的情况:stackoverflow.com/questions/68503586/…
-
我不认为
#pragma omp simd应该提供任何加速,即使indices更大,因为您正在内部循环中进行收集操作,我无法想象从矢量化中获利。
标签: c++ performance parallel-processing openmp