user69818
user69818

Reputation: 403

How to properly time an ocaml program?

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.

Upvotes: 0

Views: 518

Answers (1)

ivg
ivg

Reputation: 35280

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)

Upvotes: 2

Related Questions