[Haskell-cafe] Optimization demonstration

Dušan Kolář kolar at fit.vut.cz
Tue Feb 27 15:06:33 UTC 2018


Dear Café,

	I'm trying to do very small, but impressive example about optimizations 
possible during Haskell compilation. So far, I can demonstrate that the following two 
programs (if compiled) perform computation in the same time:

1)

main =
    putStrLn $ show $ sum $ map (*(2::Int)) [(1::Int)..(100000000::Int)]


2)

main =
    putStrLn $! show $! sumup 1 0

sumup :: Int -> Int -> Int
sumup n total =
    if n<=(100000000::Int) then sumup (n+1) $! total+(2*n)
    else total


Nevertheless, I expect a question on comparison with C:

3)

#include <stdio.h>

int main(void) {
   long sum, i;
   sum = 0;
   for (i=1; i <= 100000000L; ++i) {
       sum += 2*i;
   }
   printf("%ld\n",sum);
   return 0;
}


Unfortunately, in this case the C is much more faster (it prints the result immediately), at 
least on my machine. Is it due to a fact that C compiler does a brutal optimization leading 
to compile-time evaluation, while ghc is not able to do that?

I'm using -O2 -dynamic --make ghc compiler flags. For gcc for C compilation just -O2, 
running Arch Linux.

Is there any option, how to force compile time evaluation? The reason, why I think it works 
this way is the fact, that when running out of long type values in C a code is generated 
that computes the values regularly (providing misleading value as a result) taking its time.

Best regards,

Dušan



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20180227/0fb87452/attachment.html>


More information about the Haskell-Cafe mailing list