I\'m trying to learn how to use the Control.Parallel
module, but I think I didn\'t get it right.
I\'m trying to run the following code (fibs.hs).>
As Don explained, the problem is that you are creating too many sparks. Here's how you might rewrite it to get a good speedup.
import Control.Parallel
cutoff :: Int
cutoff = 20
parFib :: Int -> Int
parFib n | n < cutoff = fib n
parFib n = p `par` q `pseq` (p + q)
where
p = parFib $ n - 1
q = parFib $ n - 2
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
main :: IO ()
main = print $ parFib 40
demonstration:
[computer ~]$ ghc --make -threaded -O2 Main.hs
[1 of 1] Compiling Main ( Main.hs, Main.o )
Linking Main ...
[computer ~]$ time ./Main +RTS -N1
102334155
real 0m1.509s
user 0m1.450s
sys 0m0.003s
[computer ~]$ time ./Main +RTS -N2
102334155
real 0m0.776s
user 0m1.487s
sys 0m0.023s
[computer ~]$ time ./Main +RTS -N3
102334155
real 0m0.564s
user 0m1.487s
sys 0m0.030s
[computer ~]$ time ./Main +RTS -N4
102334155
real 0m0.510s
user 0m1.587s
sys 0m0.047s
[computer ~]$