gpt4 book ai didi

c - OpenMP 和 C 并行 for 循环 : why does my code slow down when using OpenMP?

转载 作者:太空狗 更新时间:2023-10-29 16:52:14 25 4
gpt4 key购买 nike

我是新来的,是 C 语言的初级程序员。我在使用 openmp 加速 for 循环时遇到了一些问题。下面是一个简单的例子:

#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <omp.h>

gsl_rng *rng;

main()
{
int i, M=100000000;
double tmp;

/* initialize RNG */
gsl_rng_env_setup();
rng = gsl_rng_alloc (gsl_rng_taus);
gsl_rng_set (rng,(unsigned long int)791526599);

// option 1: parallel
#pragma omp parallel for default(shared) private( i, tmp ) schedule(dynamic)
for(i=0;i<=M-1;i++){
tmp=gsl_ran_gamma_mt(rng, 4, 1./3 );
}


// option 2: sequential
for(i=0;i<=M-1;i++){
tmp=gsl_ran_gamma_mt(rng, 4, 1./3 );
}
}

代码从 M 次迭代的 Gamma 随机分布中提取。事实证明,使用 openmp 的并行方法(选项 1)大约需要 1 分钟,而顺序方法(选项 2)只需要 20 秒。使用 openmp 运行时,我可以看到 cpu 使用率为 800%(我使用的服务器有 8 个 CPU)。系统是带有 GCC 4.1.3 的 linux。我使用的编译命令是 gcc -fopenmp -lgsl -lgslcblas -lm (我使用的是 GSL)

我做错了什么吗?请帮我!谢谢!

附言正如一些用户所指出的,这可能是由 rng 引起的。但即使我更换

tmp=gsl_ran_gamma_mt(rng, 4, 1./3 );

tmp=1000*10000;

问题依然存在...

最佳答案

gsl_ran_gamma_mt 可能会锁定 rng 以防止并发问题(如果没有,您的并行代码可能包含竞争条件并因此产生错误的结果)。解决方案是为每个线程设置一个单独的 rng 实例,从而避免锁定。

关于c - OpenMP 和 C 并行 for 循环 : why does my code slow down when using OpenMP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12095564/

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