Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running time in Ocaml

Tags:

time

ocaml

How to figure out the amount of time my code has taken in ocaml? are there any functions to measure that?

like image 817
priyanka Avatar asked Jan 30 '12 08:01

priyanka


3 Answers

If you want to measure execution time of individual functions, this utility function is helpful in many cases:

let time f x =
    let t = Sys.time() in
    let fx = f x in
    Printf.printf "Execution time: %fs\n" (Sys.time() -. t);
    fx

where f is any function which takes x as the argument and returns something.

like image 200
pad Avatar answered Oct 18 '22 19:10

pad


In my own coding, I use Unix.gettimeofday (), which returns a float value with a resolution of much less than one second. It's described in the documentation for the OCaml Unix module. Despite the name of the module, this function also works in Windows (and probably in almost all environments you might encounter).

If I rewrite pad's answer I get the following code:

let time f x =
    let start = Unix.gettimeofday ()
    in let res = f x
    in let stop = Unix.gettimeofday ()
    in let () = Printf.printf "Execution time: %fs\n%!" (stop -. start)
    in
       res
like image 29
Jeffrey Scofield Avatar answered Oct 18 '22 19:10

Jeffrey Scofield


You can use Sys.time(). It returns the processor time, in seconds, used by the program since the beginning of execution.

Source : http://caml.inria.fr/pub/docs/manual-ocaml/libref/Sys.html

like image 4
Kevin Avatar answered Oct 18 '22 18:10

Kevin