首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >par无作用

par无作用
EN

Stack Overflow用户
提问于 2017-05-14 02:12:27
回答 1查看 115关注 0票数 2

我很难在Haskell中完成并行计算。我只是尝试了一个非常简单的并行和非并行形式的计算,而非并行的计算要快几秒。我做错了什么吗?知道为什么会这样吗?提前谢谢。

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

代码语言:javascript
复制
-- par.hs
import Control.Parallel
a = sum [1, 3 ..  99999999]
b = sum [2, 4 .. 100000000]
main = (a `par` b) `pseq` print (a + b)

这是非平行版本:

代码语言:javascript
复制
-- nopar.hs
a = sum [1, 3 ..  99999999]
b = sum [2, 4 .. 100000000]
main = print (a + b)

但是当我尝试的时候,并行化没有,甚至没有负面的效果:

代码语言:javascript
复制
➜  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 
EN

回答 1

Stack Overflow用户

发布于 2017-05-14 09:59:43

IIUC,@Carl和@Zeta的评论组合如下:

代码语言:javascript
复制
 $ 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

为了了解原因,下面是一些真实世界Haskell的摘录

默认情况下,GHC生成的程序只使用一个核心,即使我们编写显式并发代码时也是如此。要使用多核,我们必须明确地选择这样做。在生成可执行程序时,我们在链接时做出这个选择。..。如果我们将-threaded选项传递给编译器,它将将我们的程序链接到线程运行时库。

我们可以在程序的命令行上将选项传递给GHC的运行时系统。在将控制交给我们的代码之前,运行时会扫描程序的参数以获得特殊的命令行选项+RTS。..。线程运行库接受一个选项-N。这需要一个参数,它指定GHC的运行时系统应该使用的核心数量。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43959754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档