Sunday, 20 May 2007

OCaml whups Lisp on Pythagorean Triplets micro-benchmark

Giovanni Intini recently posted a great suite of programs written in C, Ruby, Erlang and Python that count the number of Pythagorean triplets (a^2 = b^2 + c^2 for integers a, b and c<n):

This micro-benchmark quickly caught the attention of programmers from various backgrounds and snowballed into a miniature language comparison.

We submitted a simple OCaml implementation that turned out to be roughly as fast as the C implementation (faster than -O2 but slower than -O3 -ffast-math) and slightly shorter:

let n = 5000
let () =
let i = ref 0 in
for c=2 to n do
for b=1 to c-1 do
let a = sqrt(float(c*c - b*b)) in
if float(truncate a) = a then incr i
print_endline (string_of_int !i)
After several days of conferring and much performance-related deliberation, the Lisp community announced their completion of a longer and slower but "more flexible" solution written in Lisp.

For a thorough introduction to high-performance computing using OCaml, read OCaml for Scientists.


intinig said...

Thanks for the link, I was amazed by the speed of Ocaml, a language I didn't even consider before yesterday :)

Phil Tomson said...

I posted this question on one of the older threads, and I'll repeat it here:

I'm curious: Would it be possible to use camlp4r to create an F# "frontend" for OCaml? If it were possible, then one could use OCaml for both F# and OCaml. It would also allow the compilation of F# on Linux.

I'm concerned that F# will split the rather small OCaml community since they're very similar. But if something like this could be accomplished then F# would just be a dialect of OCaml.

Jon Harrop said...

Under the surface, the OCaml and F# languages are sufficiently different that it is not possible to convert between them using macros.

More specifically, their type systems are quite different. The most notable difference being the support for overloading and nomally-subtyped objects in F#, and polymorphic variants and structurally-subtyped objects in OCaml.

I wouldn't worry about splitting the OCaml community. The OCaml programming language is developed and primarily used under Linux (we use Linux extensively here). In constrast, the F# language is (as you imply) developed and primarily used under Windows.

If anything, I think the two communities will supplement each other.

Also, the OCaml community is much larger than the F# community and we are still making far more money from our OCaml-related work than from our F# work.