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?

This small OCaml function is handy:

let time f =
  let t = Unix.gettimeofday () in
  let res = f () in
  Printf.printf "Execution time: %f secondsn"
                (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 by Eric Z Ma.

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *