How to configure ocaml correctly?

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 into bytecode. The runtime seems to be a few seconds, but the program prints 0.000001.

And if I replaced Unix.gettimeofday () with Sys.time (), then it is only 0.000000s.

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

I wonder what is wrong here? I am in Debian Wheezy and the ocaml version is 4.02.1.

0
source share
1 answer

The arguments to the printf function, as well as any other function, are evaluated in an unspecified order. In your case, the expression (Unix.gettimeofday () -. t) evaluates to (nothing 0) . A more appropriate 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: %gs\n" (Unix.gettimeofday() -. t) 
+2
source

All Articles