Note that there are some explanatory texts on larger screens.

plurals
  1. POPython faster than compiled Haskell?
    text
    copied!<p>I have a simple script written in both Python and Haskell. It reads a file with 1,000,000 newline separated integers, parses that file into a list of integers, quick sorts it and then writes it to a different file sorted. This file has the same format as the unsorted one. Simple.</p> <p>Here is Haskell:</p> <pre><code>quicksort :: Ord a =&gt; [a] -&gt; [a] quicksort [] = [] quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater) where lesser = filter (&lt; p) xs greater = filter (&gt;= p) xs main = do file &lt;- readFile "data" let un = lines file let f = map (\x -&gt; read x::Int ) un let done = quicksort f writeFile "sorted" (unlines (map show done)) </code></pre> <p>And here is Python:</p> <pre class="lang-python prettyprint-override"><code>def qs(ar): if len(ar) == 0: return ar p = ar[0] return qs([i for i in ar if i &lt; p]) + [p] + qs([i for i in ar if i &gt; p]) def read_file(fn): f = open(fn) data = f.read() f.close() return data def write_file(fn, data): f = open('sorted', 'w') f.write(data) f.close() def main(): data = read_file('data') lines = data.split('\n') lines = [int(l) for l in lines] done = qs(lines) done = [str(l) for l in done] write_file('sorted', "\n".join(done)) if __name__ == '__main__': main() </code></pre> <p>Very simple. Now I compile the Haskell code with</p> <pre><code>$ ghc -O2 --make quick.hs </code></pre> <p>And I time those two with:</p> <pre><code>$ time ./quick $ time python qs.py </code></pre> <p>Results:</p> <p>Haskell:</p> <pre><code>real 0m10.820s user 0m10.656s sys 0m0.154s </code></pre> <p>Python:</p> <pre><code>real 0m9.888s user 0m9.669s sys 0m0.203s </code></pre> <p>How can Python possibly be faster than native code Haskell?</p> <p>Thanks</p> <p><strong>EDIT</strong>:</p> <ul> <li>Python version: 2.7.1</li> <li>GHC version: 7.0.4</li> <li>Mac OSX, 10.7.3</li> <li>2.4GHz Intel Core i5</li> </ul> <p>List generated by</p> <pre class="lang-python prettyprint-override"><code>from random import shuffle a = [str(a) for a in xrange(0, 1000*1000)] shuffle(a) s = "\n".join(a) f = open('data', 'w') f.write(s) f.close() </code></pre> <p>So all numbers are unique.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload