[Haskell-cafe] Re: newbie optimization question

Peter Hercek peter at syncad.com
Mon Oct 29 04:19:34 EDT 2007


Derek Elkins wrote:
> 
> Try with rem instead of mod.
> 
> (What the heck is with bottom?)

The bottom was there by error and I was lazy to redo
  the tests so I rather posted exactly what I was
  doing. I do not know the compiler that good to be
  absolutely sure it cannot have impact on result
  ... so I rather did not doctor what I did :-)

Ok, rem did help quite a bit. Any comments why it is so?

Here are summary of results for those interested. I run
  all the tests once again. Haskell was about 13% slower
  than C++.

MS cl.exe options: /Ox /G7 /MD
ghc options: -O2

C++ version:  1.000; 0.984; 0.984
Haskell version specialized to Int: 1.125; 1.125; 1.109
Haskell version specialized to Integer: 8.781; 8.813; 8.813
Haskell version specialized to Int64: 9.781; 9.766; 9.831

The code:

% cat b.hs
module Main (divisors, perfect, main) where
import Data.Int

divisors :: Int -> [Int]
divisors i = [j | j<-[1..i-1], i `rem` j == 0]

perfect :: [Int]
perfect = [i | i<-[1..10000], i == sum (divisors i)]

main = print perfect

% cat b.cpp
#include <iostream>
using namespace std;

int main() {
   for (int i = 1; i <= 10000; i++) {
     int sum = 0;
     for (int j = 1; j < i; j++)
       if (i % j == 0)
         sum += j;
     if (sum == i)
       cout << i << " ";
   }
   return 0;
}

%



More information about the Haskell-Cafe mailing list