How to measure a function's execution time in OCaml?

How to measure the execution time of a function, say f: 'a -> 'b in OCaml?

asked Jan 2, 2015 by Eric Z Ma (44,280 points)

1 Answer

 
Best answer

This small OCaml function is handy:

let time f =
  let t = Unix.gettimeofday () in
  let res = f () in
  Printf.printf "Execution time: %f seconds\n"
                (Unix.gettimeofday () -. t);
  res
;;

The gettimeofday returns a float representing the time with resolution better than 1 second:

val gettimeofday : unit -> float
Same as Unix.time, but with resolution better than 1 second.

-- http://caml.inria.fr/pub/docs/manual-ocaml/libref/Unix.html

For example, to measure the execution time of this naive Fibonacci function implementation

let rec fib n = if n < 3 then 1 else fib (n-1) + fib (n-2);;

when n = 40, you can

time (fun () -> fib 20);;

In the toplevel, it will print results like:

Execution time: 3.352741 seconds
- : int = 102334155
answered Jan 2, 2015 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Related questions

1 answer
1 answer
1 answer
1 answer
asked Dec 14, 2013 by anonymous
1 answer
1 answer
1 answer
asked May 2, 2013 by Adam (1,780 points)
Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...