为什么我的 OpenMP 实现比单线程实现慢?
我正在学习 OpenMP 并发性,并尝试了一些现有的代码。在此代码中,我尝试使所有 for 循环并行。然而,这似乎使程序慢得多,至少慢 10 倍,甚至比单线程版本慢得多。
这是代码: http://pastebin.com/zyLzuWU2
我还使用了pthreads,事实证明它更快比单线程版本。
现在的问题是,我在 OpenMP 实现中做错了什么导致速度变慢?
谢谢!
编辑:单线程版本只是没有所有#pragmas 的版本
I am learning about OpenMP concurrency, and tried my hand at some existing code I have. In this code, I tried to make all the for loops parallel. However, this seems to make the program MUCH slower, at least 10x slower, or even more than the single threaded version.
Here is the code: http://pastebin.com/zyLzuWU2
I also used pthreads, which turns out to be faster than the single threaded version.
Now the question is, what am I doing wrong in my OpenMP implementation that is causing this slowdown?
Thanks!
edit: the single threaded version is just the one without all the #pragmas
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现您的代码存在一个问题,即您在非常小的循环(例如 8 或 64 次迭代)中使用 OpenMP。由于开销,这不会有效。如果您想使用 OpenMP 解决 n 皇后问题,请查看 OpenMP 3.0 任务和分支定界问题的线程并行性。
One problem I see with your code is that you are using OpenMP across loops that are very small (8 or 64 iterations, for example). This will not be efficient due to overheads. If you want to use OpenMP for the n-queens problem, look at OpenMP 3.0 tasks and thread parallelism for branch-and-bound problems.
我认为您的代码太复杂,无法在这里进行审查。我立即发现的一个错误是它甚至不正确。在使用
omp parallel for
进行求和的地方,您必须使用reduction(+: yourcountervariable)
才能将不同线程的结果正确地组合在一起。否则,一个线程可能会覆盖其他线程的结果。I think your code is much too complex to be reviewed here. One error that I saw immediately is that it is not even correct. At places where you are using an
omp parallel for
to do sums you must usereduction(+: yourcountervariable)
to have the results of the different threads correctly assembled together. Otherwise one thread may overwrite the result of the others.至少有两个原因:
您只对一个非常简单的循环进行 8 次迭代。您的运行时将完全由设置所有线程所涉及的开销主导。
在某些地方,
临界
部分会引起争用;所有线程都会不断地尝试访问临界区,并互相阻塞。At least two reasons:
You're only doing 8 iterations of a very simple loop. Your runtime will be completely dominated by the overhead involved in setting up all the threads.
In some places, the
critical
section will cause contention; all the threads will be trying to access the critical section continuously, and block each other.