(* timer functions *)
let print_buffer = ref []

let init_times  () = print_buffer := []

(* do total time *)
let time reps s f =
  let initial = Sys.time() in
  let result = f () in
  let final =
     (for i=1 to reps-1 do f() done;
      Sys.time ()) in
  let elapsed = (final -. initial) *. 1000.0 /. (float reps) in
  print_buffer := (fun () -> (Format.fprintf Format.std_formatter 
                               "-- %s: iterations:%d avg time:%E msec"
			         s reps elapsed; (Format.print_newline ())))
		  :: !print_buffer;
  result

let timenew s f =
  let reps = ref 1 in
  let initial = Sys.time() in
  let result = f () in
  while (Sys.time() -. initial < 1.0)
  do f() done;
  let elapsed = (Sys.time() -. initial) *. 1000.0 /. (float !reps) in
  print_buffer := (fun () -> (Format.fprintf Format.std_formatter 
                               "-- %s: iterations:%d avg time:%E msec"
                                 s !reps elapsed; (Format.print_newline ())))
                  :: !print_buffer;
  result

let print_times () =
  List.iter (fun f -> f ()) (List.rev !print_buffer);
  init_times()
