Debian Codegraph @

lib/newProfile.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 module MiniJson = struct
12 type t =[
13 | `Intlit of string
14 | `String of string
15 | `Assoc of (string * t) list
16 | `List of t list
17 ]
18
19 (* https://www.ietf.org/rfc/rfc4627.txt *)
20 (* https://github.com/ocaml-community/yojson/blob/4c1d4b52f9e87a4bd3b7f26111e8a4976c1e8676/lib/write.ml#L27 *)
21 let prstring ch s =
22 let buf = Buffer.create (String.length s) in
23 let encode c =
24 match c with
25 | '"' -> Buffer.add_string buf "\\\""
26 | '\\' -> Buffer.add_string buf "\\\\"
27 | '\b' -> Buffer.add_string buf "\\b"
28 | '\012' -> Buffer.add_string buf "\\f"
29 | '\n' -> Buffer.add_string buf "\\n"
30 | '\r' -> Buffer.add_string buf "\\r"
31 | '\t' -> Buffer.add_string buf "\\t"
32 | '\x00'..'\x1F'
33 | '\x7F' ->
34 Buffer.add_string buf (Printf.sprintf "\\u%04x" (Char.code c))
35 | _ -> Buffer.add_char buf c
36 in
37 String.iter encode s;
38 Format.fprintf ch "\"%s\"" (Buffer.contents buf)
39
40 let rec pr ch : t -> _ = function
41 | `String s -> prstring ch s
42 | `Intlit s -> Format.fprintf ch "%s" s
43 | `Assoc elts ->
44 Format.fprintf ch "{ %a }" prrecord elts
45 | `List elts ->
46 Format.fprintf ch "[\n%a\n]" prarray elts
47
48 and prrecord ch = function
49 | [] -> ()
50 | [(x,v)] -> Format.fprintf ch "%a: %a" prstring x pr v
51 | (x,v) :: l -> Format.fprintf ch "%a: %a, %a" prstring x pr v prrecord l
52
53 and prarray ch = function
54 | [] -> ()
55 | [x] -> pr ch x
56 | x :: l -> Format.fprintf ch "%a,\n%a" pr x prarray l
57
58
59 let pid = Unix.getpid()
60
61 let pids = string_of_int pid
62 let base = [("pid", `Intlit pids); ("tid", `Intlit pids)]
63
64 let duration ~name ~ph ~ts ?args () =
65 let l = ("name", `String name) :: ("ph", `String ph) :: ("ts", `Intlit ts) :: base in
66 let l = match args with
67 | None -> l
68 | Some args -> ("args", `Assoc args) :: l
69 in
70 `Assoc l
71 end
72
73 type sums = (float * int) CString.Map.t
74
75 let empty_sums : sums = CString.Map.empty
76
77 let sums_union a b =
78 CString.Map.union (fun _name (l,cnt) (r,cnt') ->
79 Some (l +. r, cnt + cnt'))
80 a b
81
82 type accu = {
83 output : Format.formatter option;
84 accumulate : MiniJson.t list ref option;
85 mutable sums : (float * sums) list;
86 }
87
88 let accu = ref None
89
90 let is_profiling () = Option.has_some !accu
91
92 let gettime = Unix.gettimeofday
93
94 let gettimeopt = function
95 | Some t -> t
96 | None -> gettime()
97
98 let prtime t =
99 Format.sprintf "%.0f" (t *. 1E6)
100
101 module Counters = struct
102
103 (* time is handled separately because it has special status in the output format *)
104 type t = {
105 major_words : float;
106 minor_words : float;
107 major_collections : int;
108 minor_collections : int;
109 instr : System.instruction_count;
110 }
111
112 let zero = {
113 major_words = 0.;
114 minor_words = 0.;
115 major_collections = 0;
116 minor_collections = 0;
117 instr = Ok 0L;
118 }
119
120 let get () =
121 let gc = Gc.quick_stat() in
122 {
123 major_words = gc.major_words;
124 minor_words = gc.minor_words;
125 major_collections = gc.major_collections;
126 minor_collections = gc.minor_collections;
127 instr = Instr.read_counter();
128 }
129
130 let global_start = get ()
131
132 let (+) a b = {
133 major_words = a.major_words +. b.major_words;
134 minor_words = a.minor_words +. b.minor_words;
135 major_collections = a.major_collections + b.major_collections;
136 minor_collections = a.minor_collections + b.minor_collections;
137 instr = System.instruction_count_add a.instr b.instr;
138 }
139
140 let (-) b a = {
141 major_words = b.major_words -. a.major_words;
142 minor_words = b.minor_words -. a.minor_words;
143 major_collections = b.major_collections - a.major_collections;
144 minor_collections = b.minor_collections - a.minor_collections;
145 instr = System.instructions_between ~c_start:a.instr ~c_end:b.instr;
146 }
147
148 let print x =
149 let open Pp in
150 let ppw diff = str (Format.sprintf "%.3G words" diff) in
151 v 0 @@
152 prlist_with_sep spc (fun x -> hov 0 x)
153 ((str "major words:" ++ spc() ++ ppw x.major_words) ::
154 (str "minor words:" ++ spc() ++ ppw x.minor_words) ::
155 (str "major collections:" ++ spc() ++ int x.major_collections) ::
156 (str "minor collections:" ++ spc() ++ int x.minor_collections) ::
157 match x.instr with
158 | Ok count -> [str "instructions:" ++ spc() ++ str (Int64.to_string count)]
159 | Error _ -> [])
160
161 let format x =
162 let ppw diff = `String (Format.sprintf "%.3G w" diff) in
163 let ppi i = `Intlit (string_of_int i) in
164 let instr = match x.instr with
165 | Ok count -> [("instr", `Intlit (Int64.to_string count))]
166 | Error _ -> []
167 in
168 ("major_words",ppw x.major_words) ::
169 ("minor_words", ppw x.minor_words) ::
170 ("major_collect", ppi x.major_collections) ::
171 ("minor_collect", ppi x.minor_collections) ::
172 instr
173
174 let make_diffs ~start ~stop = format (stop - start)
175
176 end
177
178 let global_start_time = gettime ()
179
180 let output_event json ?(last=",") () =
181 let accu = Option.get !accu in
182 accu.output |> Option.iter (fun ch ->
183 Format.fprintf ch "%a%s\n" MiniJson.pr json last);
184 accu.accumulate |> Option.iter (fun out ->
185 out := json :: !out)
186
187 let duration ~time name ph ?args ?last () =
188 let duration = MiniJson.duration ~name ~ph ~ts:(prtime time) ?args () in
189 output_event duration ?last ()
190
191 let enter_sums ?time () =
192 let accu = Option.get !accu in
193 let time = gettimeopt time in
194 accu.sums <- (time, CString.Map.empty) :: accu.sums
195
196 let enter ?time name ?args () =
197 let time = gettimeopt time in
198 enter_sums ~time ();
199 duration ~time name "B" ?args ()
200
201 let leave_sums ?time name () =
202 let accu = Option.get !accu in
203 let time = gettimeopt time in
204 match accu.sums with
205 | [] -> assert false
206 | [start,sum] -> accu.sums <- []; sum, time -. start
207 | (start, sum) :: (start', next) :: rest ->
208 let dur = time -. start in
209 let next = CString.Map.update name (function
210 | None -> Some (dur, 1)
211 | Some (dur', cnt) -> Some (dur +. dur', cnt+1))
212 next
213 in
214 let next = CString.Map.union (fun name' (l,cnt) (r,cnt') ->
215 if String.equal name name' then Some (r,cnt+cnt')
216 else Some (l +. r, cnt+cnt'))
217 sum next
218 in
219 accu. sums <- (start', next) :: rest;
220 sum, dur
221
222 let rec pptime fmt t = let open Format in function
223 | [] -> assert false
224 | [unit] ->
225 if t >= 1. then fprintf fmt "%03.0f%s" t unit
226 else fprintf fmt "0%s" unit
227 | unit :: nextunit :: rest ->
228 (* float t is time in [unit] *)
229 if t >= 1. then fprintf fmt "%03.0f%s %03.0f%s" t unit (Float.rem (t *. 1_000.) 1_000.) nextunit
230 else pptime fmt (t *. 1_000.) (nextunit :: rest)
231
232 let pptime fmt t = pptime fmt t ["s";"ms";"us";"ns"]
233
234 let leave ?time name ?(args=[]) ?last () =
235 let time = gettimeopt time in
236 let sum, dur = leave_sums ~time name () in
237 let sum = CString.Map.bindings sum in
238 let sum = List.sort (fun (_,(t1,_)) (_,(t2,_)) -> Float.compare t2 t1) sum in
239 let sum = List.map (fun (name, (t, cnt)) ->
240 name, `String
241 (Format.asprintf "%a, %d %s" pptime t cnt (CString.plural cnt "call")))
242 sum
243 in
244 let args = ("subtimes", `Assoc sum) :: args in
245 duration ~time name "E" ~args ?last ()
246
247 (* NB: "process" and "init" are unconditional because they don't go
248 through [profile] and I'm too lazy to make them conditional *)
249 let components = ref CString.Pred.empty
250
251 let profile name ?args f () =
252 if not (is_profiling ()) then f ()
253 else if CString.Pred.mem name !components then begin
254 let args = Option.map (fun f -> f()) args in
255 enter name ?args ();
256 let start = Counters.get () in
257 let v = try f ()
258 with e ->
259 let e = Exninfo.capture e in
260 let args = Counters.make_diffs ~start ~stop:(Counters.get()) in
261 leave name ~args ();
262 Exninfo.iraise e
263 in
264 let args = Counters.make_diffs ~start ~stop:(Counters.get()) in
265 leave name ~args ();
266 v
267 end
268 else begin
269 enter_sums ();
270 let v = try f ()
271 with e ->
272 let e = Exninfo.capture e in
273 ignore (leave_sums name () : _ * _);
274 Exninfo.iraise e
275 in
276 ignore (leave_sums name () : _ * _);
277 v
278 end
279
280 let format_header ch =
281 Format.fprintf ch "{ \"traceEvents\": [\n"
282
283 let format_footer ch =
284 Format.fprintf ch "],\n\"displayTimeUnit\": \"us\" }@."
285
286 type settings =
287 { output : Format.formatter;
288 fname : string;
289 }
290
291 let init_components () =
292 let s = Envars.getenv_rocq "_PROFILE_COMPONENTS" in
293 let s = Option.default "-unification,Conversion" s in
294 let v =
295 if CString.is_prefix "-" s then
296 List.fold_left (fun cs c -> CString.Pred.remove c cs)
297 CString.Pred.full
298 (String.split_on_char ',' (CString.sub s 1 (String.length s - 1)))
299 else
300 List.fold_left (fun cs c -> CString.Pred.add c cs)
301 CString.Pred.empty
302 (String.split_on_char ',' s)
303 in
304 components := v
305
306 let init { output; fname; } =
307 let () = assert (not (is_profiling())) in
308 init_components();
309 accu := Some { output = Some output; accumulate = None; sums = []; };
310 format_header output;
311 enter ~time:global_start_time ~args:["fname", `String fname] "process" ();
312 enter ~time:global_start_time "init" ();
313 let args = Counters.(make_diffs ~start:global_start ~stop:(get())) in
314 leave "init" ~args ()
315
316 let pause () =
317 let v = !accu in
318 accu := None;
319 v
320
321 let resume v =
322 assert (not (is_profiling()));
323 accu := Some v
324
325 let finish () = match !accu with
326 | None | Some { output = None } -> assert false
327 | Some { output = Some ch } ->
328 let args = Counters.(make_diffs ~start:global_start ~stop:(get())) in
329 leave "process" ~last:"" ~args ();
330 format_footer ch;
331 accu := None
332
333 let insert_sums sums =
334 let accu = Option.get !accu in
335 match accu.sums with
336 | [] -> assert false
337 | (start, sums') :: rest ->
338 let sums = sums_union sums sums' in
339 accu.sums <- (start, sums) :: rest
340
341 let insert_results events sums =
342 List.iter (fun e -> output_event e ()) events;
343 insert_sums sums
344
345 let with_profiling f =
346 let out = ref [] in
347 let this_accu, old_accu = match !accu with
348 | None ->
349 init_components();
350 { output = None;
351 accumulate = Some out;
352 sums = [0., empty_sums];
353 }
354 , None
355 | Some accu ->
356 { output = accu.output;
357 accumulate = Some out;
358 sums = [0., empty_sums];
359 }
360 , Some accu
361 in
362 let finally () =
363 let out = List.rev !out in
364 let sums = match this_accu.sums with
365 | [_, x] -> x
366 | _ -> assert false
367 in
368 accu := old_accu;
369 let () = match old_accu with
370 | None -> ()
371 | Some accu ->
372 (* events have already been output to the formatter if there is one *)
373 accu.accumulate |> Option.iter (fun accumulate ->
374 accumulate := List.rev_append out !accumulate);
375 insert_sums sums
376 in
377 out, sums
378 in
379 accu := Some this_accu;
380 let v = try f () with e ->
381 let e = Exninfo.capture e in
382 ignore (finally() : _ * _);
383 Exninfo.iraise e
384 in
385
386 let out, sums = finally () in
387
388 out, sums, v