How to properly time an ocaml program?

孤街浪徒 提交于 2019-12-12 01:56:52

问题


let t = Unix.gettimeofday()
let rec nothing i =
  match i with
  | 1000000000 -> 1
  | _ -> nothing (i+1)
let () = Printf.printf "%d %fs\n" (nothing 0) (Unix.gettimeofday() -. t)

I use the command

ocamlc unix.cma test.ml

to compile it to bytecode. The execution time is apparently several seconds, but the program prints 0.000001s.

And if I replace Unix.gettimeofday() with Sys.time(), it is just 0.000000s.

Running the code in utop is not much better. It gives about 0.02s, while I count at least 5s.

I am wondering what goes wrong here? I am on Debian Wheezy and ocaml version is 4.02.1.


回答1:


Arguments to printf function, as well as to any other function are evaluated in an unspecified order. In your case the (Unix.gettimeofday () -. t) expression is evaluated before the the (nothing 0). A more proper version of the code would be:

let rec nothing i =
  match i with
  | 1000000000 -> 1
  | _ -> nothing (i+1)


let () =
  let t = Unix.gettimeofday() in 
  Printf.printf "%ds\n" (nothing 0);
  Printf.printf "time elapsed: %g s\n" (Unix.gettimeofday() -. t)


来源:https://stackoverflow.com/questions/27652007/how-to-properly-time-an-ocaml-program

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