Skip to content

Instantly share code, notes, and snippets.

@jtpaasch
Created May 4, 2018 00:40
Show Gist options
  • Select an option

  • Save jtpaasch/2729ec784f9419e218e51e98d63958b7 to your computer and use it in GitHub Desktop.

Select an option

Save jtpaasch/2729ec784f9419e218e51e98d63958b7 to your computer and use it in GitHub Desktop.
A simple module to time functions (OCaml)
(* Assume a module called [Proc.Cmd] with a [run] function is loaded. *)
(* Compile with the [unix.cma/cmxa] module. *)
module Timer = struct
let time f x =
let start = Unix.gettimeofday () in
let result = f x in
let stop = Unix.gettimeofday () in
let delta = stop -. start in
(delta, result)
let rec repeat count n results f x =
let result = time f x in
match (count < n) with
| false -> results
| true ->
repeat (count + 1) n (results @ [result]) f x
let rec sumf l acc =
match l with
| [] -> acc
| h :: t -> sumf t (acc +. h)
let deltas l = List.map (fun x -> fst(x)) l
let total_time l =
let times = deltas l in
sumf times 0.0
let avg l =
let num_trials = List.length l in
let total = total_time l in
total /. (float_of_int (num_trials))
end
let () =
Printf.printf "Starting...\n%!";
let cmd = "sleep 2" in
let trials = Timer.repeat 0 3 [] Ps.Cmd.run cmd in
List.iter (fun x ->
let get_delta (n, _) = n in
let get_result (_, n) = n in
let get_exit_code (n, _, _) = n in
let get_stdout (_, n, _) = n in
let delta = get_delta x in
let result = get_result x in
Printf.printf "----\n%!";
Printf.printf "exit code: %d\n%!" (get_exit_code result);
Printf.printf "stdout:\n%s\n%!" (Ps.Buff.contents (get_stdout result));
Printf.printf "Time: %.3f\n%!" delta)
trials;
let avg_time = Timer.avg trials in
Printf.printf "Avg time: %.3f\n%!" avg_time;
let total_time = Timer.total_time trials in
Printf.printf "Total time: %.3f\n%!" total_time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment