2

I am trying a basic microbenchmark comparison of c with ocaml. I have heard that for the fibonacci program, c and ocaml are about the same, but I can't replicate those results. I compile the c code with gcc -O3 fib.c -o c-code, and compile the OCaml code with ocamlopt -o ocaml-code fibo.ml. I am timing by using time ./c-code and time ./ocaml-code. Every time I do this OCaml takes 0.10 seconds whereas the c code is about .03 seconds each time. Besides the fact that this is a naive benchmark, is there a way to make ocaml faster? Can anyone see what the times on their computers are?

C

#include <stdio.h>

int fibonacci(int n)
{
    return n<3 ? 1 : fibonacci(n-1) + fibonacci(n-2);
}

int main(void)
{
    printf("%d", fibonacci(34));
    return 0;
}

OCaml

let rec fibonacci n = if n < 3 then 1 else fibonacci(n-1) + fibonacci(n-2);;
print_int(fibonacci 34);;
LTigger
  • 21
  • 2
  • Have you looked at [this very similar question](http://stackoverflow.com/questions/4121790/stack-performance-in-programming-languages) ? It includes detailed bench results for ocaml, and links to test code. – Francois G Jan 17 '11 at 01:32
  • 1
    Yes I Have looked at that. I ran the C code which was about .05 seconds whereas the ocaml code is .15 seconds. – LTigger Jan 17 '11 at 02:18

2 Answers2

6

The ML version already beats the C version when compiled with gcc -O2, which I think is a pretty decent job. Looking at the assembly generated by gcc -O3, it looks like gcc is doing some aggressive inlining and loop unrolling. To make the code faster, I think you would have to rewrite the code, but you should focus on higher level abstraction instead.

Wei Hu
  • 2,888
  • 2
  • 27
  • 28
2

I think this is just an overhead to ocaml, it would be more relevant to compare with a larger program.

You can use the -S option to produce assembly output, along with -verbose to see how ocaml calls external applications (gcc). Additionally, using the -p option and running your application through gprof will help determine if this is an overhead from ocaml, or something you can actually improve.

Cheers.

For my computer I get the following,

ocaml - 0.035 (std-dev=0.02; 10 trials)  
    c - 0.027 (std-dev=0.03; 10 trials)  
nlucaroni
  • 47,556
  • 6
  • 64
  • 86