Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to improve the performance of this Haskell program?
    primarykey
    data
    text
    <p>I'm working through the problems in <a href="http://projecteuler.net/" rel="noreferrer">Project Euler</a> as a way of learning Haskell, and I find that my programs are a lot slower than a comparable C version, even when compiled. What can I do to speed up my Haskell programs?</p> <p>For example, my brute-force solution to <a href="http://projecteuler.net/index.php?section=problems&amp;id=14" rel="noreferrer">Problem 14</a> is:</p> <pre><code>import Data.Int import Data.Ord import Data.List searchTo = 1000000 nextNumber :: Int64 -&gt; Int64 nextNumber n | even n = n `div` 2 | otherwise = 3 * n + 1 sequenceLength :: Int64 -&gt; Int sequenceLength 1 = 1 sequenceLength n = 1 + (sequenceLength next) where next = nextNumber n longestSequence = maximumBy (comparing sequenceLength) [1..searchTo] main = putStrLn $ show $ longestSequence </code></pre> <p>Which takes around 220 seconds, while an "equivalent" brute-force C version only takes 1.2 seconds.</p> <pre><code>#include &lt;stdio.h&gt; int main(int argc, char **argv) { int longest = 0; int terms = 0; int i; unsigned long j; for (i = 1; i &lt;= 1000000; i++) { j = i; int this_terms = 1; while (j != 1) { this_terms++; if (this_terms &gt; terms) { terms = this_terms; longest = i; } if (j % 2 == 0) j = j / 2; else j = 3 * j + 1; } } printf("%d\n", longest); return 0; } </code></pre> <p>What am I doing wrong? Or am I naive to think that Haskell could even approach C's speed?</p> <p>(I'm compiling the C version with gcc -O2, and the Haskell version with ghc --make -O).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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