Docsity

Improving Fibonacci Function Performance with Functional Parallelism, Study notes of Computer Science

Partial preview of the text

Download Improving Fibonacci Function Performance with Functional Parallelism and more Study notes Computer Science in PDF only on Docsity!

CS 457/557: Functional

Languages

An Introduction to Control.Parallel

Mark P Jones

Portland State University

A Silly, Slow Program:

fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) nfib 0 = 1 nfib 1 = 1 nfib n = 1 + nfib (n-1) + nfib (n-2) diffib n = nfib n - fib n main = print (diffib 38) 2

Introducing Control.Parallel:

par :: a -> b -> b

par x y is semantically just y, but hints to the compiler that it might be useful to start evaluating x

pseq :: a -> b -> b

pseq x y is semantically just y, but will evaluate x before returning a result

A Silly, Parallel Program:

fib 0 = … nfib 0 = … diffib n = let l = nfib n r = fib n in par l (l - r) main = print (diffib 38)

On Multiple Cores:

prompt$ ./par1a +RTS -s -N 87403802 prompt$ cat par1a.stat 16,759,034,636 bytes allocated in the heap 11,618,096 bytes copied during GC (scavenged) 2,878,584 bytes copied during GC (not scavenged) 24,576 bytes maximum residency (2 sample(s)) INIT time 0.00s ( 0.00s elapsed) MUT time 16.47s ( 16.89s elapsed) GC time 0.25s ( 0.33s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 16.73s ( 17.23s elapsed) prompt$

A Different, Silly Program:

fib 0 = … nfib 0 = … diffib n = let l = nfib n r = fib n in par r (l - r) main = print (diffib 38)

A More Robust, Silly Program:

fib 0 = … nfib 0 = … diffib n = let l = nfib n r = fib n in par l (pseq r (l - r)) main = print (diffib 38)

A More Robust, Silly Program:

fib 0 = … nfib 0 = … diffib n = let l = nfib n r = fib n in l par r pseq (l-r) main = print (diffib 38)

Back to Fractals:

Leveraging Parallelism:

sample :: Grid Point -> Image color -> Grid color sample points image = map (map image) points This looks like a good candidate for parallelization … But how?

Control.Parallel.Strategies:

class NFData a where

rnf :: Strategy a

rnf is a strategy for reducing values to normal form

instance NFData Int where …

instance NFData Bool where …

instance NFData a => NFData [a]

where …

16

Control.Parallel.Strategies:

parList

:: Strategy a -> Strategy [a]

Evaluate a list in parallel, using the argument strategy for each element. parMap :: Strategy b -> (a -> b) -> [a] -> [b] parMap s f xs = map f xs using parList s

Adopting a Strategy:

sample :: NFData color => Grid Point -> Image color -> Grid color sample points image = map (map image) points using parList rnf (also need to add an NFData color context to the type of draw)

Adopting a Strategy:

sample :: Grid Point -> Image color -> Grid color sample points image = map (map image) points draw pal grid render = render (sample grid (fracImage pal) using parList rnf)