5

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

nlucaroni
  • 47,556
  • 6
  • 64
  • 86
UnSat
  • 1,347
  • 2
  • 14
  • 28
  • Possible duplicate of [Running time in Ocaml](https://stackoverflow.com/questions/9061421/running-time-in-ocaml) – Mars Aug 23 '17 at 02:59

3 Answers3

11

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
Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
  • This is a crucial distinction. Thanks for highlighting it. One might want either kind of time, but you definitely don't want to mix them up if they differ. – Mars Sep 07 '17 at 05:41
8
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.

user3075773
  • 139
  • 1
  • 5
2

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.

Daniel Bünzli
  • 5,119
  • 20
  • 21