Debian Codegraph @

engine/profile_tactic.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 open Unicode
12 open Pp
13 open Util
14
15 module M = CString.Map
16
17 let profile_ltac = ref false
18 let profile_ltac_cutoff = ref 2.0
19
20 (** [is_profiling] and the profiling info ([stack]) should be synchronized with
21 the document; the rest of the ref cells are either local to individual
22 tactic invocations, or global flags, and need not be synchronized, since no
23 document-level backtracking happens within tactics. We synchronize
24 is_profiling via an option. *)
25 let is_profiling = profile_ltac
26
27 let set_profiling b = is_profiling := b
28 let get_profiling () = !is_profiling
29
30 let get_profiling_cutoff () = string_of_float !profile_ltac_cutoff
31 let set_profiling_cutoff s =
32 try profile_ltac_cutoff := float_of_string s
33 with Failure _ -> CErrors.user_err Pp.(str "Ltac Profiling Cutoff must be interpretable as a float.")
34
35 let encountered_invalid_stack_no_self = ref false
36
37 let warn_invalid_stack_no_self =
38 CWarnings.create ~name:"profile-invalid-stack-no-self" ~category:CWarnings.CoreCategories.ltac
39 (fun () -> strbrk
40 "Ltac Profiler encountered an invalid stack (no self \
41 node). This can happen if you reset the profile during \
42 tactic execution.")
43
44 let encounter_invalid_stack_no_self () =
45 if not !encountered_invalid_stack_no_self
46 then begin
47 encountered_invalid_stack_no_self := true;
48 warn_invalid_stack_no_self ()
49 end
50
51
52 (* *************** tree data structure for profiling ****************** *)
53
54 type treenode = {
55 name : string;
56 total : float;
57 local : float;
58 ncalls : int;
59 max_total : float;
60 children : treenode M.t
61 }
62
63 let empty_treenode name = {
64 name;
65 total = 0.0;
66 local = 0.0;
67 ncalls = 0;
68 max_total = 0.0;
69 children = M.empty;
70 }
71
72 let root = "root"
73
74
75 let stack = Summary.ref ~name:"LtacProf-stack" ~local:true [empty_treenode root]
76
77 let reset_profile_tmp () = stack := [empty_treenode root]
78
79 (* ************** XML Serialization ********************* *)
80
81 let rec of_ltacprof_tactic (name, t) =
82 assert (String.equal name t.name);
83 let open Xml_datatype in
84 let total = string_of_float t.total in
85 let local = string_of_float t.local in
86 let ncalls = string_of_int t.ncalls in
87 let max_total = string_of_float t.max_total in
88 let children = List.map of_ltacprof_tactic (M.bindings t.children) in
89 Element ("ltacprof_tactic",
90 [ ("name", name); ("total",total); ("local",local);
91 ("ncalls",ncalls); ("max_total",max_total)],
92 children)
93
94 let of_ltacprof_results t =
95 let open Xml_datatype in
96 assert(String.equal t.name root);
97 let children = List.map of_ltacprof_tactic (M.bindings t.children) in
98 Element ("ltacprof", [("total_time", string_of_float t.total)], children)
99
100 let rec to_ltacprof_tactic m xml =
101 let open Xml_datatype in
102 match xml with
103 | Element ("ltacprof_tactic",
104 [("name", name); ("total",total); ("local",local);
105 ("ncalls",ncalls); ("max_total",max_total)], xs) ->
106 let node = {
107 name;
108 total = float_of_string total;
109 local = float_of_string local;
110 ncalls = int_of_string ncalls;
111 max_total = float_of_string max_total;
112 children = List.fold_left to_ltacprof_tactic M.empty xs;
113 } in
114 M.add name node m
115 | _ -> CErrors.anomaly Pp.(str "Malformed ltacprof_tactic XML.")
116
117 let to_ltacprof_results xml =
118 let open Xml_datatype in
119 match xml with
120 | Element ("ltacprof", [("total_time", t)], xs) ->
121 { name = root;
122 total = float_of_string t;
123 ncalls = 0;
124 max_total = 0.0;
125 local = 0.0;
126 children = List.fold_left to_ltacprof_tactic M.empty xs }
127 | _ -> CErrors.anomaly Pp.(str "Malformed ltacprof XML.")
128
129 let feedback_results results =
130 Feedback.(feedback
131 (Custom (None, "ltacprof_results", of_ltacprof_results results)))
132
133 (* ************** pretty printing ************************************* *)
134
135 let format_sec x = (Printf.sprintf "%.3fs" x)
136 let format_ratio x = (Printf.sprintf "%.1f%%" (100. *. x))
137 let padl n s = ws (max 0 (n - utf8_length s)) ++ str s
138 let padr_with c n s =
139 let ulength = utf8_length s in
140 if Int.equal n ulength then str s
141 else if n < ulength then str (utf8_sub s 0 n)
142 else str s ++ str (String.make (n - ulength) c)
143
144 let rec list_map_is_last f = function
145 | [] -> []
146 | [x] -> [f true x]
147 | x :: xs -> f false x :: list_map_is_last f xs
148
149 let repeat_str n s =
150 if String.is_empty s then s
151 else
152 let len = String.length s in
153 String.init (n * len) (fun i -> s.[i mod len])
154
155 let header_name = " tactic"
156 let header_name_width = utf8_length header_name
157
158 let header_rest = "┴──────┴──────┴───────┴─────────┘"
159 let header_rest_width = utf8_length header_rest
160
161 let header name_width =
162 str " tactic" ++ str (String.make (name_width - header_name_width) ' ') ++ str " local total calls max" ++
163 fnl () ++
164 str (repeat_str name_width "─") ++ str header_rest ++
165 fnl ()
166
167 module Line = struct
168 type t = {
169 prefix : string;
170 tac_name : string;
171 local : float;
172 total : float;
173 calls : int;
174 maxtime : float;
175 }
176
177 let pr ~name_width l =
178 h (
179 padr_with '-' name_width (l.prefix ^ l.tac_name ^ " ")
180 ++ padl 7 (format_ratio l.local)
181 ++ padl 7 (format_ratio l.total)
182 ++ padl 8 (string_of_int l.calls)
183 ++ padl 10 (format_sec l.maxtime))
184 end
185
186 let rec linearize_node ~filter all_total indent prefix (s, e) =
187 { Line.prefix; tac_name=s;
188 local = (e.local /. all_total);
189 total = (e.total /. all_total);
190 calls = e.ncalls;
191 maxtime = e.max_total;
192 } :: linearize_table ~filter all_total indent false e.children
193
194 and linearize_table ~filter all_total indent first_level table =
195 let fold _ n l =
196 let s, total = n.name, n.total in
197 if filter s total then (s, n) :: l else l in
198 let ls = M.fold fold table [] in
199 match ls with
200 | [s, n] when not first_level ->
201 linearize_node ~filter all_total indent (indent ^ "└") (s, n)
202 | _ ->
203 let ls =
204 List.sort (fun (_, { total = s1 }) (_, { total = s2}) ->
205 compare s2 s1) ls in
206 let iter is_last =
207 let sep0 = if first_level then "" else if is_last then " " else " │" in
208 let sep1 = if first_level then "─" else if is_last then " └─" else " ├─" in
209 linearize_node ~filter all_total (indent ^ sep0) (indent ^ sep1)
210 in
211 List.concat (list_map_is_last iter ls)
212
213 let get_printing_width = ref (fun () -> Format.pp_get_margin Format.std_formatter ())
214
215 let set_get_printing_width f = get_printing_width := f
216 let get_printing_width () = !get_printing_width ()
217
218 let print_table ~filter all_total table =
219 let lines = linearize_table ~filter all_total "" true table in
220 let name_width = List.fold_left (fun acc (l:Line.t) ->
221 max acc (utf8_length (l.prefix ^ l.tac_name)))
222 0
223 lines
224 in
225 let name_width = name_width + 1 (* +1 for a space at the end *) in
226 (* respect Printing Width unless it's so short that we can't print the header correctly *)
227 let name_width = min (get_printing_width() - header_rest_width) name_width in
228 let name_width = max header_name_width name_width in
229 header name_width ++
230 prlist_with_sep fnl (Line.pr ~name_width) lines
231
232 let to_string ~filter ~cutoff node =
233 let tree = node.children in
234 let all_total = M.fold (fun _ { total } a -> total +. a) node.children 0.0 in
235 let flat_tree =
236 let global = ref M.empty in
237 let find_tactic tname l =
238 try M.find tname !global
239 with Not_found ->
240 let e = empty_treenode tname in
241 global := M.add tname e !global;
242 e in
243 let add_tactic tname stats = global := M.add tname stats !global in
244 let sum_stats add_total
245 { name; total = t1; local = l1; ncalls = n1; max_total = m1 }
246 { total = t2; local = l2; ncalls = n2; max_total = m2 } = {
247 name;
248 total = if add_total then t1 +. t2 else t1;
249 local = l1 +. l2;
250 ncalls = n1 + n2;
251 max_total = if add_total then max m1 m2 else m1;
252 children = M.empty;
253 } in
254 let rec cumulate table =
255 let iter _ ({ name; children } as statistics) =
256 if filter name then begin
257 let stats' = find_tactic name global in
258 add_tactic name (sum_stats true stats' statistics);
259 end;
260 cumulate children
261 in
262 M.iter iter table
263 in
264 cumulate tree;
265 !global
266 in
267 let filter s n = filter s && (all_total <= 0.0 || n /. all_total >= cutoff /. 100.0) in
268 let msg =
269 h (str "total time: " ++ padl 11 (format_sec (all_total))) ++
270 fnl () ++
271 fnl () ++
272 print_table ~filter all_total flat_tree ++
273 fnl () ++ fnl () ++
274 print_table ~filter all_total tree
275 in
276 msg
277
278 (* ******************** profiling code ************************************** *)
279
280 let get_child name node =
281 try M.find name node.children
282 with Not_found -> empty_treenode name
283
284 let time () =
285 let times = Unix.times () in
286 times.Unix.tms_utime +. times.Unix.tms_stime
287
288 let string_of_call ck =
289 let s = string_of_ppcmds ck in
290 let s = String.map (fun c -> if c = '\n' then ' ' else c) s in
291 let s = try String.sub s 0 (CString.string_index_from s 0 "(*") with Not_found -> s in
292 String.trim s
293
294 let rec merge_sub_tree name tree acc =
295 try
296 let t = M.find name acc in
297 let t = {
298 name;
299 total = t.total +. tree.total;
300 ncalls = t.ncalls + tree.ncalls;
301 local = t.local +. tree.local;
302 max_total = max t.max_total tree.max_total;
303 children = M.fold merge_sub_tree tree.children t.children;
304 } in
305 M.add name t acc
306 with Not_found -> M.add name tree acc
307
308 let merge_roots ?(disjoint=true) t1 t2 =
309 assert(String.equal t1.name t2.name);
310 { name = t1.name;
311 ncalls = t1.ncalls + t2.ncalls;
312 local = if disjoint then t1.local +. t2.local else t1.local;
313 total = if disjoint then t1.total +. t2.total else t1.total;
314 max_total = if disjoint then max t1.max_total t2.max_total else t1.max_total;
315 children =
316 M.fold merge_sub_tree t2.children t1.children }
317
318 let rec find_in_stack what acc = function
319 | [] -> None
320 | { name } as x :: rest when String.equal name what -> Some(acc, x, rest)
321 | { name } as x :: rest -> find_in_stack what (x :: acc) rest
322
323 let exit_tactic ~count_call start_time name =
324 let diff = time () -. start_time in
325 match !stack with
326 | [] | [_] ->
327 (* oops, our stack is invalid *)
328 encounter_invalid_stack_no_self ();
329 reset_profile_tmp ()
330 | node :: (parent :: rest as full_stack) ->
331 if not (String.equal name node.name) then
332 (* oops, our stack is invalid *)
333 CErrors.anomaly
334 (Pp.strbrk "Ltac Profiler encountered an invalid stack (wrong self node) \
335 likely due to backtracking into multi-success tactics.");
336 let node = { node with
337 total = node.total +. diff;
338 local = node.local +. diff;
339 ncalls = node.ncalls + (if count_call then 1 else 0);
340 max_total = max node.max_total diff;
341 } in
342 (* updating the stack *)
343 let parent =
344 match find_in_stack node.name [] full_stack with
345 | None ->
346 (* no rec-call, we graft the subtree *)
347 let parent = { parent with
348 local = parent.local -. diff;
349 children = M.add node.name node parent.children } in
350 stack := parent :: rest;
351 parent
352 | Some(to_update, self, rest) ->
353 (* we coalesce the rec-call and update the lower stack *)
354 let self = merge_roots ~disjoint:false self node in
355 let updated_stack =
356 List.fold_left (fun s x ->
357 (try M.find x.name (List.hd s).children
358 with Not_found -> x) :: s) (self :: rest) to_update in
359 stack := updated_stack;
360 List.hd !stack
361 in
362 (* Calls are over, we reset the stack and send back data *)
363 if rest == [] && get_profiling () then begin
364 assert(String.equal root parent.name);
365 encountered_invalid_stack_no_self := false;
366 reset_profile_tmp ();
367 feedback_results parent
368 end
369
370 (** [tclWRAPFINALLY before tac finally] runs [before] before each
371 entry-point of [tac] and passes the result of [before] to
372 [finally], which is then run at each exit-point of [tac],
373 regardless of whether it succeeds or fails. Said another way, if
374 [tac] succeeds, then it behaves as [before >>= fun v -> tac >>= fun
375 ret -> finally v <*> tclUNIT ret]; otherwise, if [tac] fails with
376 [e], it behaves as [before >>= fun v -> finally v <*> tclZERO
377 e]. *)
378 let rec tclWRAPFINALLY before tac finally =
379 let open Proofview in
380 let open Proofview.Notations in
381 before >>= fun v -> tclCASE tac >>= function
382 | Fail (e, info) -> finally v >>= fun () -> tclZERO ~info e
383 | Next (ret, tac') -> tclOR
384 (finally v >>= fun () -> tclUNIT ret)
385 (fun e -> tclWRAPFINALLY before (tac' e) finally)
386
387 let do_profile_gen pp_call call_trace ?(count_call=true) tac =
388 let open Proofview.Notations in
389 (* We do an early check to [is_profiling] so that we save the
390 overhead of [tclWRAPFINALLY] when profiling is not set
391 *)
392 Proofview.tclLIFT (Proofview.NonLogical.make (fun () -> !is_profiling)) >>= function
393 | false -> tac
394 | true ->
395 tclWRAPFINALLY
396 (Proofview.tclLIFT (Proofview.NonLogical.make (fun () ->
397 match pp_call call_trace, !stack with
398 | Some c, parent :: rest ->
399 let name = string_of_call c in
400 let node = get_child name parent in
401 stack := node :: parent :: rest;
402 Some (name, time ())
403 | Some _, [] -> assert false
404 | _ -> None
405 )))
406 tac
407 (function
408 | Some (name, start_time) ->
409 (Proofview.tclLIFT (Proofview.NonLogical.make (fun () ->
410 exit_tactic ~count_call start_time name)))
411 | None -> Proofview.tclUNIT ())
412
413 (* ************** Accumulation of data from workers ************************* *)
414
415 let get_local_profiling_results () = List.hd !stack
416
417 (* We maintain our own cache of document data, given that the
418 semantics of the STM implies that synchronized state for opaque
419 proofs will be lost on QED. This provides some complications later
420 on as we will have to simulate going back on the document on our
421 own. *)
422 module DData = struct
423 type t = Feedback.doc_id * Stateid.t
424 let compare x y = compare x y
425 end
426
427 module SM = Map.Make(DData)
428
429 let data = ref SM.empty
430
431 let _ =
432 Feedback.(add_feeder (function
433 | { doc_id = d;
434 span_id = s;
435 contents = Custom (_, "ltacprof_results", xml) } ->
436 let results = to_ltacprof_results xml in
437 let other_results = (* Multi success can cause this *)
438 try SM.find (d,s) !data
439 with Not_found -> empty_treenode root in
440 data := SM.add (d,s) (merge_roots results other_results) !data
441 | _ -> ()))
442
443 let reset_profile () =
444 encountered_invalid_stack_no_self := false;
445 reset_profile_tmp ();
446 data := SM.empty
447
448 (* ****************************** Named timers ****************************** *)
449
450 let timer_data = ref M.empty
451
452 let timer_name = function
453 | Some v -> v
454 | None -> ""
455
456 let restart_timer name =
457 timer_data := M.add (timer_name name) (System.get_time ()) !timer_data
458
459 let get_timer name =
460 try M.find (timer_name name) !timer_data
461 with Not_found -> System.get_time ()
462
463 let finish_timing ~prefix name =
464 let tend = System.get_time () in
465 let tstart = get_timer name in
466 Feedback.msg_notice(str prefix ++ pr_opt str name ++ str " ran for " ++
467 System.fmt_time_difference tstart tend)
468
469 (* ******************** *)
470
471 let print_results_filter ~cutoff ~filter =
472 let cutoff = Option.default !profile_ltac_cutoff cutoff in
473 data := SM.filter (fun (doc,id) _ -> Stateid.is_valid ~doc id) !data;
474 let results =
475 SM.fold (fun _ -> merge_roots ~disjoint:true) !data (empty_treenode root) in
476 let results = merge_roots results (CList.last !stack) in
477 Feedback.msg_notice (to_string ~cutoff ~filter results)
478 ;;
479
480 let print_results ~cutoff =
481 print_results_filter ~cutoff ~filter:(fun _ -> true)
482
483 let print_results_tactic tactic =
484 print_results_filter ~cutoff:None ~filter:(fun s ->
485 String.(equal tactic (sub (s ^ ".") 0 (min (1+length s) (length tactic)))))
486
487 let do_print_results_at_close () =
488 if get_profiling () then print_results ~cutoff:None
489
490 let () =
491 let open Goptions in
492 declare_bool_option
493 { optstage = Summary.Stage.Interp;
494 optdepr = None;
495 optkey = ["Ltac"; "Profiling"];
496 optread = get_profiling;
497 optwrite = set_profiling }
498
499 let () =
500 let open Goptions in
501 declare_string_option
502 { optstage = Summary.Stage.Interp;
503 optdepr = None;
504 optkey = ["Ltac"; "Profiling"; "Cutoff"];
505 optread = get_profiling_cutoff;
506 optwrite = set_profiling_cutoff }