Search code examples
ocamlocaml-toplevel

OCaml: measure execution time in toplevel


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


Solution

  • 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