Running time in Ocaml

后端 未结 3 1524
挽巷
挽巷 2020-12-11 01:46

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

相关标签:
3条回答
  • 2020-12-11 02:26

    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.

    0 讨论(0)
  • 2020-12-11 02:28

    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
    
    0 讨论(0)
  • 2020-12-11 02:35

    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

    0 讨论(0)
提交回复
热议问题