Skip to content

Instantly share code, notes, and snippets.

@luishendrix92
Created March 9, 2024 17:47
Show Gist options
  • Save luishendrix92/f9b9e035f3be5c9f23707512128f9161 to your computer and use it in GitHub Desktop.
Save luishendrix92/f9b9e035f3be5c9f23707512128f9161 to your computer and use it in GitHub Desktop.
Measure execution time of a function in milliseconds at runtime
(** [bench work] runs a function [work] and returns the amount of milliseconds
it took to finish. Uses [Sys.time] to mark the start and end of execution. *)
let bench work =
let start_time = Sys.time () in
work ();
let end_time = Sys.time () in
(end_time -. start_time) *. 1000.0
;;
(* Let's give it a test run! *)
Printf.printf "100M item list construction took %f ms.\n"
@@ bench @@ fun () ->
let xs : int list ref = ref [] in
for i = 1 to 100_000_000 do
xs := i :: !xs
done;
(*> Computing the 10th fibonacci sequence number took 5260.875000 ms. *)
;;
(* Or testing an existing function *)
let rec fib = function
| 0 -> 0
| 1 -> 1
| n -> fib (n - 1) + fib (n - 2)
;;
Printf.printf "Computing the 41th fibonacci sequence number took %f ms.\n"
@@ bench @@ fun () -> fib 10
(* Computing the 10th fibonacci sequence number took 10452.497000 ms. *)
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment