Skip to content

Instantly share code, notes, and snippets.

@watermouth
Created June 7, 2013 15:13
Show Gist options
  • Select an option

  • Save watermouth/5729993 to your computer and use it in GitHub Desktop.

Select an option

Save watermouth/5729993 to your computer and use it in GitHub Desktop.
performance check key-value pair access using - direct array - array through key array and match function - Hashtbl
type currency_t = JPY | USD | EUR | AUD | GBP
let to_int ccy = match ccy with
| JPY -> 0
| USD -> 1
| EUR -> 2
| AUD -> 3
| GBP -> 4
let currencies = [|JPY;USD;EUR;AUD;GBP|]
let currency_length = 5
let a = Array.init currency_length (fun i -> 10 * i)
let memo =
let h = Hashtbl.create 5 in
(Hashtbl.add h JPY 0;
Hashtbl.add h USD 10;
Hashtbl.add h EUR 20;
Hashtbl.add h AUD 30;
Hashtbl.add h GBP 40;
h)
let loop_pure_array n =
let max_i = currency_length - 1 in
let result = ref 0.0 in
for i=1 to n do
for j=0 to max_i do
result := !result +. (float_of_int (a.(j)))
done
done;
!result
let loop_array n =
let max_i = currency_length - 1 in
let result = ref 0.0 in
for i=1 to n do
for j=0 to max_i do
result := !result +. (float_of_int a.((to_int (currencies.(j)))))
done
done;
!result
let loop_hash n =
let max_i = currency_length - 1 in
let result = ref 0.0 in
for i=1 to n do
for j=0 to max_i do
result := !result +. (float_of_int (Hashtbl.find memo (currencies.(j))))
done
done;
!result
let iteration_number =
(int_of_string (Sys.argv.(1)))
let target =
(Sys.argv.(2))
let f = match target with
| "hash" -> loop_hash
| "pure_array" -> loop_pure_array
| "array" -> loop_array
| _ -> failwith "hoge"
let _ =
let result = (f iteration_number) in
Printf.printf "result = %f\n" result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment