Skip to content

Instantly share code, notes, and snippets.

@donut
Last active June 22, 2023 15:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donut/ef7003064d380e6aa1b57eb636572567 to your computer and use it in GitHub Desktop.
Save donut/ef7003064d380e6aa1b57eb636572567 to your computer and use it in GitHub Desktop.
Times different methods for calculating the number of digits of an integer.
#load "unix.cma";;
open Printf;;
let by_string x =
x |> string_of_int |> String.length
;;
let rec by_recursion = function
| 0 -> 1
| x -> 1 + by_recursion (x / 10)
;;
let by_loop x =
let x' = ref x in
let digits = ref 0 in
while !x' > 0 do
digits := !digits + 1;
x' := !x' / 10;
if !x' == 0 then digits := !digits + 1
done;
!digits
;;
let by_log x =
x |> float_of_int |> log10 |> floor |> (+.) 1. |> int_of_float
;;
let test_method times name func =
let rec test func = function
| 0 -> ()
| x -> func x; test func (x - 1)
in
let start = Unix.gettimeofday () in
printf "Testing %s method with %d...\n" name times;
test func times;
let stop = Unix.gettimeofday () in
printf "...finished in %.8f seconds\n" (stop -. start);
;;
let main () =
let test = test_method 100_000_000 in
test "string" by_string;
test "recursion" by_recursion;
test "loop" by_loop;
test "log" by_log;
;;
main ();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment