[Shootout-list] Haskell killer prodcons implementation - fair?
Einar Karttunen
ekarttun@cs.helsinki.fi
Sat, 2 Oct 2004 14:32:57 +0300
Hello
The following ghc prodcons implementation tests to 0.028 sec (with
N=150000) on my machine. This means that it is maybe the fastests
existing for prodcons. Now for the real question - is it fair?
The used concurrency abstraction MVar is the basic one in concurrent
haskell. The code is overcommented to help people with less haskell
experience.
- Einar Karttunen
-- $Id: prodcons.ghc,v 1.3 2004/06/30 07:29:01 bfulgham Exp $
-- http://shootout.alioth.debian.org/
-- by JP Bernardy, optimized by Einar Karttunen
-- Just the normal imports
import Control.Concurrent
import Control.Monad
import System
-- write integers 1 to n in the given mvar.
-- putMVar will block until the mvar is empty and
-- only then write the value.
producer n mv = mapM_ (putMVar mv) [1..n]
-- read n integers from the given mvar, return the last of them.
-- replicateM_ is just a loop, verified to be linear to N.
-- takeMVar waits tilll the mvar is filled with a value and
-- then takes the value, leaving the mvar empty.
consumer n mv = do replicateM_ (n-1) (takeMVar mv)
takeMVar mv
main = do [a] <- getArgs
let n = read a :: Int
mvar <- newEmptyMVar -- create an empty mvar
forkIO (producer n mvar) -- spawn the producing thread...
m <- consumer n mvar -- and read what it writes.
putStrLn (show n ++ " " ++ show m)