Note that there are some explanatory texts on larger screens.

plurals
  1. POHaskell - Optimizing differential equation solver
    text
    copied!<p>I'm learning Haskell and am trying to write code as fast as I can do in C. For this exercise, I'm writing a <a href="http://en.wikipedia.org/wiki/Euler_method" rel="noreferrer">Euler integrator</a> for a simple one-dimensional physical system.</p> <ul> <li>The C code is compiled with GCC 4.5.4 and <code>-O3</code>. It runs in <b>1.166</b> seconds.</li> <li>The Haskell code is compiled with GHC 7.4.1 and <code>-O3</code>. It runs in <b>21.3</b> seconds.</li> <li>If I compile Haskell with <code>-O3 -fllvm</code>, it runs in <b>4.022</b> seconds.</li> </ul> <p>So, am I missing something to optimize my Haskell code?</p> <p><b>PS.:</b> I used the following arguments: <code>1e-8 5</code>.</p> <p>C code:</p> <pre><code>#include &lt;stdio.h&gt; double p, v, a, t; double func(double t) { return t * t; } void euler(double dt) { double nt = t + dt; double na = func(nt); double nv = v + na * dt; double np = p + nv * dt; p = np; v = nv; a = na; t = nt; } int main(int argc, char ** argv) { double dt, limit; sscanf(argv[1], "%lf", &amp;dt); sscanf(argv[2], "%lf", &amp;limit); p = 0.0; v = 0.0; a = 0.0; t = 0.0; while(t &lt; limit) euler(dt); printf("%f %f %f %f\n", p, v, a, t); return 0; } </code></pre> <p>Haskell Code:</p> <pre><code>import System.Environment (getArgs) data EulerState = EulerState !Double !Double !Double !Double deriving(Show) type EulerFunction = Double -&gt; Double main = do [dt, l] &lt;- fmap (map read) getArgs print $ runEuler (EulerState 0 0 0 0) (**2) dt l runEuler :: EulerState -&gt; EulerFunction -&gt; Double -&gt; Double -&gt; EulerState runEuler s@(EulerState _ _ _ t) f dt limit = let s' = euler s f dt in case t `compare` limit of LT -&gt; s' `seq` runEuler s' f dt limit _ -&gt; s' euler :: EulerState -&gt; EulerFunction -&gt; Double -&gt; EulerState euler (EulerState p v a t) f dt = (EulerState p' v' a' t') where t' = t + dt a' = f t' v' = v + a'*dt p' = p + v'*dt </code></pre>
 

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