Running time in Ocaml

时光毁灭记忆、已成空白 提交于 2019-12-04 00:40:42

问题


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


回答1:


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.




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/9061421/running-time-in-ocaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!