【发布时间】:2018-06-13 15:32:05
【问题描述】:
我希望运行一种需要生成随机数的蒙特卡罗模拟,以及基于这些随机数的一组指令。
我希望使用并行处理,但在测试我的代码(用 C 编写)时,似乎有更多内核的反向加速!我不确定我做错了什么。然后我复制了another answer的代码形式,还是得到了这个效果。
代码稍作修改,答案是
#define NRANDS 1000000
int main() {
int a[NRANDS];
#pragma omp parallel default(none) shared(a)
{
int i;
unsigned int myseed = omp_get_thread_num();
#pragma omp for
for(i=0; i<NRANDS; i++)
a[i] = rand_r(&myseed);
}
double sum = 0.;
for (long int i=0; i<NRANDS; i++) {
sum += a[i];
}
printf("sum = %lf\n", sum);
return 0;
}
我刚刚在终端中运行time 命令以计算运行时间。我使用export OMP_NUM_THREADS=2 改变了允许的线程数。我的终端的输出是:
Thread total: 1
sum = 1074808568711883.000000
real 0m0,041s
user 0m0,036s
sys 0m0,004s
Thread total: 2
sum = 1074093295878604.000000
real 0m0,037s
user 0m0,058s
sys 0m0,008s
Thread total: 3
sum = 1073700114076905.000000
real 0m0,032s
user 0m0,061s
sys 0m0,010s
Thread total: 4
sum = 1073422298606608.000000
real 0m0,035s
user 0m0,074s
sys 0m0,024s
【问题讨论】:
-
“用户”时间需要除以核心数,“系统”时间需要从“真实”时间中减去,以查看实际情况。
标签: c multithreading random parallel-processing openmp