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 ;;
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.
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);;
n = 40, you can
time (fun () -> fib 20);;
In the toplevel, it will print results like:
Execution time: 3.352741 seconds - : int = 102334155