haskell - par 没有影响

标签 haskell parallel-processing

我在 Haskell 中完成并行计算时遇到问题。我只是尝试了一种非常简单的并行和非并行形式的计算,非并行的计算快了几秒钟。难道我做错了什么?有什么想法为什么会出现这种情况吗?提前致谢。


这是我的测试代码的并行版本:

-- par.hs
import Control.Parallel
a = sum [1, 3 ..  99999999]
b = sum [2, 4 .. 100000000]
main = (a `par` b) `pseq` print (a + b)

这是非并行版本:

-- nopar.hs
a = sum [1, 3 ..  99999999]
b = sum [2, 4 .. 100000000]
main = print (a + b)

但是当我尝试时,并行化没有任何影响,甚至有负面影响:

➜  ghc par.hs
[1 of 1] Compiling Main             ( par.hs, par.o )
Linking par ...
➜  ghc nopar.hs 
[1 of 1] Compiling Main             ( nopar.hs, nopar.o )
Linking nopar ...
➜  time ./par 
5000000050000000
./par  35.02s user 12.83s system 92% cpu 51.501 total
➜  time ./nopar 
5000000050000000
./nopar  31.33s user 6.44s system 98% cpu 38.441 total 

最佳答案

IIUC,@Carl 和 @Zeta 的评论组合解决了这个问题:

 $ ghc -threaded -O2 par.hs && time ./par 
 50000005000000

 real    0m2.303s
 user    0m2.124s
 sys     0m0.176s

$ ghc par.hs && ./par +RTS -N2
Linking par ...
par: the flag -N2 requires the program to be built with -threaded
par:
par: Usage: <prog> <args> [+RTS <rtsopts> | -RTS <args>] ... --RTS <args>
par:
par:    +RTS    Indicates run time system options follow
par:    -RTS    Indicates program arguments follow
par:   --RTS    Indicates that ALL subsequent arguments will be given to the
par:            program (including any of these RTS flags)

 $ ghc -threaded -O2 par.hs && time ./par +RTS -N2
 50000005000000

 real    0m1.572s
 user    0m2.816s
 sys     0m0.296s

要了解原因,请参阅 Real World Haskell 的一些摘录

By default, GHC generates programs that use just one core, even when we write explicitly concurrent code. To use multiple cores, we must explicitly choose to do so. We make this choice at link time, when we are generating an executable program. ... If we pass the -threaded option to the compiler, it will link our program against the threaded runtime library.

We can pass options to GHC's runtime system on the command line of our program. Before handing control to our code, the runtime scans the program's arguments for the special command line option +RTS. ... The threaded runtime accepts an option -N. This takes one argument, which specifies the number of cores that GHC's runtime system should use.

关于haskell - par 没有影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43959754/

相关文章:

haskell - 如何在Agda中比较两组?

linux - 带组捕获的并行 sed

graph - 为什么 BFS 比 DFS 更适合并行化?

c - OpenMP 中数组内容的并行更新 - 并发添加元素

string - 在字符串 Haskell 之间交换字符

haskell - 难以通过 UTF8Builder 为 RIO.Logger 编写日志消息

haskell - 在 GHCi 中获取评估时间

algorithm - 没有列表功能的 Haskell foldWhile 或 reduceWhile?

parallel-processing - Julia:如何剖析并行代码

c# - parallel.foreach 和 httpclient - 奇怪的行为