【发布时间】:2011-05-16 07:26:56
【问题描述】:
我想使用 openMP 并行生成伪随机数,如下所示:
int i;
#pragma omp parallel for
for (i=0;i<100;i++)
{
printf("%d %d %d\n",i,omp_get_thread_num(),rand());
}
return 0;
我已经在 Windows 上对其进行了测试,得到了极大的加速,但每个线程生成的数字完全相同。我也在 Linux 上对其进行了测试,但速度非常慢,8 核处理器上的并行版本比顺序版本慢了大约 10 倍,但每个线程生成的数字不同。
有什么方法可以同时获得加速和不同的数字?
编辑 27.11.2010
我想我已经使用 Jonathan Dursi 帖子中的一个想法解决了这个问题。似乎以下代码在 linux 和 windows 上都可以快速运行。数字也是伪随机的。你怎么看?
int seed[10];
int main(int argc, char **argv)
{
int i,s;
for (i=0;i<10;i++)
seed[i] = rand();
#pragma omp parallel private(s)
{
s = seed[omp_get_thread_num()];
#pragma omp for
for (i=0;i<1000;i++)
{
printf("%d %d %d\n",i,omp_get_thread_num(),s);
s=(s*17931+7391); // those numbers should be choosen more carefully
}
seed[omp_get_thread_num()] = s;
}
return 0;
}
PS.:我还没有接受任何答案,因为我需要确定这个想法是好的。
【问题讨论】:
-
另外,考虑一个基于计数器的 PRNG,例如论文 "Parallel Random Numbers: As Easy as 1, 2, 3" 中描述的那些。