-
Notifications
You must be signed in to change notification settings - Fork 125
/
chrono.ml
66 lines (58 loc) · 2.25 KB
/
chrono.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
(*
Copyright © 2011 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details.
You should have received a copy of the GNU Affero General Public License
along with Opa. If not, see <http://www.gnu.org/licenses/>.
*)
(* CF mli *)
type t = { start : unit -> unit ; restart : unit -> unit ; stop : unit -> unit ; read : unit -> float ; reset : unit -> unit }
let make () = (* start , stop , read , reset *)
let c = ref 0. in (* date of the last time you started it *)
let t = ref 0. in (* cumulated time *)
let stop = ref true in
{start = (fun () -> if !stop then (stop := false ; c := Unix.gettimeofday()) else ());
stop = (fun () -> if !stop then () else (stop := true ; t := !t +. ((Unix.gettimeofday()) -. !c)));
read = (fun () -> if !stop then !t else !t +. (Unix.gettimeofday()) -. !c);
reset = (fun () -> stop := true; t := 0.);
restart = (fun () -> stop := false; t := 0. ; c := Unix.gettimeofday ())}
let start t = t.start ()
let restart t = t.restart ()
let stop t = t.stop ()
let read t = t.read ()
let reset t = t.reset ()
let print t msg =
let f = t.read () in
Printf.printf "%s: %.2fs\n%!" msg f;
t.restart ()
let measure f g =
let t0=Unix.gettimeofday() in
let res= f() in
let t1=Unix.gettimeofday() in
g (t1-.t0);
res
let measure_and_show prefix f =
measure f (fun duration -> Printf.eprintf "%s: %fs\n%!" prefix duration)
let bound timeout f when_timeout =
Sys.set_signal Sys.sigalrm (Sys.Signal_handle (fun _ -> failwith "timeout"));
ignore (Unix.alarm timeout);
try
let r = f() in
ignore (Unix.alarm 0);
r
with
| Failure "timeout" -> when_timeout()
| Stack_overflow | Out_of_memory ->
(* we must clear the still-pending alarm *)
ignore (Unix.alarm 0);
when_timeout()
| e ->
(* we must clear the still-pending alarm *)
ignore (Unix.alarm 0);
raise e