Download The demexp Book - Linux
Transcript
5.2
Timing storage
We also define a data structure used to store measured times, indexed by timer names. From all
the stored measures, we want to extract maximum, minimum and average time.
Firstly, all the timer measures as stored in a structure that records minimum and maximum
values, the sum of all recorded values as well as the number of them.
26a
hperf.ml 25ai+≡
type timer_measure = {
mutable min : float;
mutable max : float;
mutable sum : float;
mutable number : int;
}
/ 25c 26b .
The global data structure that store measures, measure storage, is a hash table from timer
names to recorded measures.
26b
hperf.ml 25ai+≡
/ 26a 26c .
let measure_storage : (string, timer_measure) Hashtbl.t = Hashtbl.create 3
(* timer_name -> measures *)
Function record measure stores a new measure delta for timer name. It simply updates
the min, max, sum and number fields of it.
26c
hperf.ml 25ai+≡
let record_measure timer_name delta =
let update_measure measure delta =
if delta < measure.min then measure.min <- delta;
if delta > measure.max then measure.max <- delta;
measure.sum <- measure.sum +. delta;
measure.number <- measure.number + 1 in
let empty_measure =
{ min = infinity; max = neg_infinity; sum = 0.; number = 0 } in
try
let m = Hashtbl.find measure_storage timer_name in
update_measure m delta
with Not_found ->
let m = empty_measure in
update_measure m delta;
Hashtbl.add measure_storage timer_name m
/ 26b 26d .
Function timer stop and record stops the timer and records the elapsed time for timer name.
26d
hperf.ml 25ai+≡
let timer_stop_and_record timer_name timer =
record_measure timer_name (timer ())
/ 26c 26e .
Function get min avg max returns the minimum, average and maximum of a recored values
stored for timer name. It raises Not found exception if no measure exists for timer name.
26e
hperf.ml 25ai+≡
/ 26d 27a .
let get_min_avg_max timer_name =
let measure = Hashtbl.find measure_storage timer_name in
(measure.min, measure.sum /. (float_of_int measure.number), measure.max)
26