[Haskell-cafe] Haskell performance question

Dan Piponi dpiponi at gmail.com
Thu Nov 8 13:33:12 EST 2007

I see lots of shootout examples where Haskell programs seem to perform
comparably with C programs, but I find it hard to reproduce anything
like those figures when testing with my own code. So here's a simple

I have this C program:

#include <stdio.h>

#define n 100000000

double a[n];

int main()
   int i;
   for (i = 0; i<n; ++i)
       a[i] = 1.0f;
   for (i = 0; i<n-1; ++i)
       a[i+1] = a[i]+a[i+1];

And this Haskell program:

import Data.Array.IO
import Control.Monad

n = 10000000

main = do
   a <- newArray (0,n-1) 1.0 :: IO (IOUArray Int Double)
   forM_ [0..n-2] $ \i -> do { x <- readArray a i; y <- readArray a
(i+1); writeArray a (i+1) (x+y) }
   x <- readArray a (n-1)
   print x

Even though 'n' is 10 times bigger in the C program it runs much
faster than the Haskell program on my MacBook Pro with Haskell 6.6.1.
I've tried lots of different combinations of flags that I've found in
various postings to haskell-cafe but to no avail.

What flags do I need to get at least within a factor of 2 or 3 of C?
Am I using the wrong kind of array? Or is Haskell always going to be
15-20 times slower for this kind of numerical work?

More information about the Haskell-Cafe mailing list