OCaml: measure execution time in toplevel

1.5k views Asked by At

How should we measure the execution time of a function in the OCaml toplevel?

3

There are 3 answers

1
Jeffrey Scofield On BEST ANSWER

As @user3075773 says, you can use Sys.time. However note that it returns processor time (CPU time). More often I want to know the wall clock time (elapsed time). You can get this from Unix.gettimeofday:

let time f x =
    let t = Unix.gettimeofday () in
    let fx = f x in
    Printf.printf "execution elapsed time: %f sec\n"
        (Unix.gettimeofday () -. t);
    fx
0
user3075773 On
let time f x =
    let t = Sys.time() in
    let fx = f x in
    Printf.printf "execution time: %fs\n" (Sys.time() -. t);
    fx

Works with any function, it will print how long did the function take to run in the toplevel.

0
Daniel Bünzli On

Using gettimeofday like the accepted answer suggests is not a good idea as it is sensitive to calendar time operating system adjustements (e.g. via ntp).

If you just want CPU time then using Sys.time is fine. If you want wall-clock time, then a monotonic time source should be used. One is available for OCaml in the mtime package.