简体   繁体   English

Haskell:顺序斐波那契比并行更快

[英]Haskell: sequential Fibonacci faster than parallel

So, I'm experimenting with parallelism in Haskell. 因此,我正在Haskell中尝试并行处理。 I took a classic example of implementing a Fibonacci sequence method both in sequential and in parallel. 我举了一个经典的示例,该示例以顺序和并行方式实现斐波那契数列方法。 here is my Main.hs file: 这是我的Main.hs文件:

module Main where
import Control.Parallel
main = print (fib 47)
fib :: Int -> Int
fib n
| n <=1 = n
| otherwise = fib (n-1) + fib (n-2)

I compile with ghc -O2 --make Main.hs -threaded -rtsopts and execute with time ./Main +RTS -N4 which gives me: 我用ghc -O2 --make Main.hs -threaded -rtsopts并随着time ./Main +RTS -N4执行time ./Main +RTS -N4这给了我:

2971215073
63.23user 13.03system 0:20.30elapsed 375%CPU (0avgtext+0avgdata 3824maxresident)k
0inputs+0outputs (0major+276minor)pagefaults 0swaps

So with normal Fibonacci it takes about 20 seconds. 因此,使用正常的斐波那契大约需要20秒。

Now if I change my fib method to 现在,如果我将fib方法更改为

pfib :: Int -> Int
pfib n
    | n <= 1 = n
    | otherwise = n1 `par` (n2 `par` n1 + n2)
        where
            n1 = pfib (n - 1)
            n2 = pfib (n - 2)

Compiling and running as above, time takes way longer and finishes with the output: 如上编译和运行, time花费更长的时间,并在输出中完成:

2971215073
179.50user 9.04system 0:53.08elapsed 355%CPU (0avgtext+0avgdata 6980maxresident)k
0inputs+0outputs (0major+1066minor)pagefaults 0swaps

Further modifying my pfib to use pseq instead of the second par , time gives: 进一步修改我的pfib以使用pseq代替第二个partime给出:

2971215073
113.34user 3.42system 0:30.91elapsed 377%CPU (0avgtext+0avgdata 7312maxresident)k
0inputs+0outputs (0major+1119minor)pagefaults 0swaps

Is there an issue with my code? 我的代码有问题吗? why do I have that illogical time difference between the various implementations? 为什么我在各种实现之间会有不合逻辑的时间差异?

From the documentation for par : par的文档中:

Also it is a good idea to ensure that a is not a trivial computation, otherwise the cost of spawning it in parallel overshadows the benefits obtained by running it in parallel. 同样,确保a不是一个微不足道的计算也是个好主意,否则,并行生成它的成本将使并行运行所获得的收益蒙上阴影。

An addition and a couple of subtractions are a trivial computation. 加法和减法是微不足道的计算。 If you only run a few levels of depth in parallel, you'll see benefits: 如果仅并行运行几个深度级别,您将看到好处:

module Main where
import Control.Parallel

main = print (pfib 16 47)

fib :: Int -> Int
fib n
    | n <= 1 = n
    | otherwise = fib (n-1) + fib (n-2)

pfib :: Int -> Int -> Int
pfib 1 n = fib n
pfib p n
    | n <= 1 = n
    | otherwise = n1 `par` (n2 `par` n1 + n2)
        where
            n1 = pfib (p - 1) (n - 1)
            n2 = pfib (p - 1) (n - 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM