How should we measure the execution time of a function in the OCaml toplevel?
OCaml: measure execution time in toplevel
1.5k Views Asked by UnSat At
3
There are 3 best solutions below
0
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
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.
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 fromUnix.gettimeofday: