]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_data_structures/src/profiling.rs
Merge tag 'debian/1.52.1+dfsg1-1_exp2' into proxmox/buster
[rustc.git] / compiler / rustc_data_structures / src / profiling.rs
CommitLineData
dfeec247
XL
1//! # Rust Compiler Self-Profiling
2//!
3//! This module implements the basic framework for the compiler's self-
4//! profiling support. It provides the `SelfProfiler` type which enables
5//! recording "events". An event is something that starts and ends at a given
6//! point in time and has an ID and a kind attached to it. This allows for
7//! tracing the compiler's activity.
8//!
9//! Internally this module uses the custom tailored [measureme][mm] crate for
10//! efficiently recording events to disk in a compact format that can be
11//! post-processed and analyzed by the suite of tools in the `measureme`
12//! project. The highest priority for the tracing framework is on incurring as
13//! little overhead as possible.
14//!
15//!
16//! ## Event Overview
17//!
18//! Events have a few properties:
19//!
20//! - The `event_kind` designates the broad category of an event (e.g. does it
21//! correspond to the execution of a query provider or to loading something
22//! from the incr. comp. on-disk cache, etc).
23//! - The `event_id` designates the query invocation or function call it
24//! corresponds to, possibly including the query key or function arguments.
25//! - Each event stores the ID of the thread it was recorded on.
26//! - The timestamp stores beginning and end of the event, or the single point
27//! in time it occurred at for "instant" events.
28//!
29//!
30//! ## Event Filtering
31//!
32//! Event generation can be filtered by event kind. Recording all possible
33//! events generates a lot of data, much of which is not needed for most kinds
34//! of analysis. So, in order to keep overhead as low as possible for a given
35//! use case, the `SelfProfiler` will only record the kinds of events that
36//! pass the filter specified as a command line argument to the compiler.
37//!
38//!
39//! ## `event_id` Assignment
40//!
41//! As far as `measureme` is concerned, `event_id`s are just strings. However,
42//! it would incur too much overhead to generate and persist each `event_id`
43//! string at the point where the event is recorded. In order to make this more
44//! efficient `measureme` has two features:
45//!
46//! - Strings can share their content, so that re-occurring parts don't have to
47//! be copied over and over again. One allocates a string in `measureme` and
48//! gets back a `StringId`. This `StringId` is then used to refer to that
49//! string. `measureme` strings are actually DAGs of string components so that
50//! arbitrary sharing of substrings can be done efficiently. This is useful
51//! because `event_id`s contain lots of redundant text like query names or
52//! def-path components.
53//!
54//! - `StringId`s can be "virtual" which means that the client picks a numeric
55//! ID according to some application-specific scheme and can later make that
56//! ID be mapped to an actual string. This is used to cheaply generate
57//! `event_id`s while the events actually occur, causing little timing
58//! distortion, and then later map those `StringId`s, in bulk, to actual
59//! `event_id` strings. This way the largest part of the tracing overhead is
60//! localized to one contiguous chunk of time.
61//!
62//! How are these `event_id`s generated in the compiler? For things that occur
63//! infrequently (e.g. "generic activities"), we just allocate the string the
64//! first time it is used and then keep the `StringId` in a hash table. This
65//! is implemented in `SelfProfiler::get_or_alloc_cached_string()`.
66//!
67//! For queries it gets more interesting: First we need a unique numeric ID for
68//! each query invocation (the `QueryInvocationId`). This ID is used as the
69//! virtual `StringId` we use as `event_id` for a given event. This ID has to
70//! be available both when the query is executed and later, together with the
71//! query key, when we allocate the actual `event_id` strings in bulk.
72//!
73//! We could make the compiler generate and keep track of such an ID for each
74//! query invocation but luckily we already have something that fits all the
75//! the requirements: the query's `DepNodeIndex`. So we use the numeric value
76//! of the `DepNodeIndex` as `event_id` when recording the event and then,
77//! just before the query context is dropped, we walk the entire query cache
78//! (which stores the `DepNodeIndex` along with the query key for each
79//! invocation) and allocate the corresponding strings together with a mapping
80//! for `DepNodeIndex as StringId`.
81//!
82//! [mm]: https://github.com/rust-lang/measureme/
83
74b04a01 84use crate::cold_path;
dfeec247
XL
85use crate::fx::FxHashMap;
86
74b04a01
XL
87use std::borrow::Borrow;
88use std::collections::hash_map::Entry;
89use std::convert::Into;
48663c56 90use std::error::Error;
dc9dc135 91use std::fs;
dc9dc135 92use std::path::Path;
532ac7d7 93use std::process;
e74abb32 94use std::sync::Arc;
dfeec247 95use std::time::{Duration, Instant};
b7449926 96
29967ef6 97use measureme::{EventId, EventIdBuilder, Profiler, SerializableString, StringId};
dfeec247 98use parking_lot::RwLock;
48663c56 99
60c5eb7d 100bitflags::bitflags! {
48663c56
XL
101 struct EventFilter: u32 {
102 const GENERIC_ACTIVITIES = 1 << 0;
103 const QUERY_PROVIDERS = 1 << 1;
104 const QUERY_CACHE_HITS = 1 << 2;
105 const QUERY_BLOCKED = 1 << 3;
106 const INCR_CACHE_LOADS = 1 << 4;
107
dfeec247 108 const QUERY_KEYS = 1 << 5;
74b04a01
XL
109 const FUNCTION_ARGS = 1 << 6;
110 const LLVM = 1 << 7;
dfeec247 111
48663c56
XL
112 const DEFAULT = Self::GENERIC_ACTIVITIES.bits |
113 Self::QUERY_PROVIDERS.bits |
114 Self::QUERY_BLOCKED.bits |
115 Self::INCR_CACHE_LOADS.bits;
74b04a01
XL
116
117 const ARGS = Self::QUERY_KEYS.bits | Self::FUNCTION_ARGS.bits;
9fa01778
XL
118 }
119}
b7449926 120
dfeec247 121// keep this in sync with the `-Z self-profile-events` help message in librustc_session/options.rs
48663c56 122const EVENT_FILTERS_BY_NAME: &[(&str, EventFilter)] = &[
dfeec247
XL
123 ("none", EventFilter::empty()),
124 ("all", EventFilter::all()),
125 ("default", EventFilter::DEFAULT),
48663c56
XL
126 ("generic-activity", EventFilter::GENERIC_ACTIVITIES),
127 ("query-provider", EventFilter::QUERY_PROVIDERS),
128 ("query-cache-hit", EventFilter::QUERY_CACHE_HITS),
dfeec247 129 ("query-blocked", EventFilter::QUERY_BLOCKED),
48663c56 130 ("incr-cache-load", EventFilter::INCR_CACHE_LOADS),
dfeec247 131 ("query-keys", EventFilter::QUERY_KEYS),
74b04a01
XL
132 ("function-args", EventFilter::FUNCTION_ARGS),
133 ("args", EventFilter::ARGS),
134 ("llvm", EventFilter::LLVM),
48663c56
XL
135];
136
dfeec247
XL
137/// Something that uniquely identifies a query invocation.
138pub struct QueryInvocationId(pub u32);
e74abb32
XL
139
140/// A reference to the SelfProfiler. It can be cloned and sent across thread
141/// boundaries at will.
142#[derive(Clone)]
143pub struct SelfProfilerRef {
144 // This field is `None` if self-profiling is disabled for the current
145 // compilation session.
146 profiler: Option<Arc<SelfProfiler>>,
147
148 // We store the filter mask directly in the reference because that doesn't
149 // cost anything and allows for filtering with checking if the profiler is
150 // actually enabled.
151 event_filter_mask: EventFilter,
dfeec247
XL
152
153 // Print verbose generic activities to stdout
154 print_verbose_generic_activities: bool,
155
156 // Print extra verbose generic activities to stdout
157 print_extra_verbose_generic_activities: bool,
e74abb32
XL
158}
159
160impl SelfProfilerRef {
dfeec247
XL
161 pub fn new(
162 profiler: Option<Arc<SelfProfiler>>,
163 print_verbose_generic_activities: bool,
164 print_extra_verbose_generic_activities: bool,
165 ) -> SelfProfilerRef {
e74abb32
XL
166 // If there is no SelfProfiler then the filter mask is set to NONE,
167 // ensuring that nothing ever tries to actually access it.
dfeec247 168 let event_filter_mask =
5869c6ff 169 profiler.as_ref().map_or(EventFilter::empty(), |p| p.event_filter_mask);
e74abb32
XL
170
171 SelfProfilerRef {
172 profiler,
173 event_filter_mask,
dfeec247
XL
174 print_verbose_generic_activities,
175 print_extra_verbose_generic_activities,
e74abb32
XL
176 }
177 }
178
179 // This shim makes sure that calls only get executed if the filter mask
180 // lets them pass. It also contains some trickery to make sure that
181 // code is optimized for non-profiling compilation sessions, i.e. anything
182 // past the filter check is never inlined so it doesn't clutter the fast
183 // path.
184 #[inline(always)]
185 fn exec<F>(&self, event_filter: EventFilter, f: F) -> TimingGuard<'_>
dfeec247
XL
186 where
187 F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
e74abb32
XL
188 {
189 #[inline(never)]
190 fn cold_call<F>(profiler_ref: &SelfProfilerRef, f: F) -> TimingGuard<'_>
dfeec247
XL
191 where
192 F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
e74abb32
XL
193 {
194 let profiler = profiler_ref.profiler.as_ref().unwrap();
195 f(&**profiler)
196 }
197
198 if unlikely!(self.event_filter_mask.contains(event_filter)) {
199 cold_call(self, f)
200 } else {
201 TimingGuard::none()
202 }
203 }
204
dfeec247
XL
205 /// Start profiling a verbose generic activity. Profiling continues until the
206 /// VerboseTimingGuard returned from this call is dropped. In addition to recording
207 /// a measureme event, "verbose" generic activities also print a timing entry to
208 /// stdout if the compiler is invoked with -Ztime or -Ztime-passes.
dfeec247
XL
209 pub fn verbose_generic_activity<'a>(
210 &'a self,
74b04a01 211 event_label: &'static str,
dfeec247 212 ) -> VerboseTimingGuard<'a> {
74b04a01
XL
213 let message =
214 if self.print_verbose_generic_activities { Some(event_label.to_owned()) } else { None };
215
216 VerboseTimingGuard::start(message, self.generic_activity(event_label))
dfeec247
XL
217 }
218
219 /// Start profiling a extra verbose generic activity. Profiling continues until the
220 /// VerboseTimingGuard returned from this call is dropped. In addition to recording
221 /// a measureme event, "extra verbose" generic activities also print a timing entry to
222 /// stdout if the compiler is invoked with -Ztime-passes.
74b04a01 223 pub fn extra_verbose_generic_activity<'a, A>(
dfeec247 224 &'a self,
74b04a01
XL
225 event_label: &'static str,
226 event_arg: A,
227 ) -> VerboseTimingGuard<'a>
228 where
229 A: Borrow<str> + Into<String>,
230 {
231 let message = if self.print_extra_verbose_generic_activities {
232 Some(format!("{}({})", event_label, event_arg.borrow()))
233 } else {
234 None
235 };
236
237 VerboseTimingGuard::start(message, self.generic_activity_with_arg(event_label, event_arg))
238 }
239
240 /// Start profiling a generic activity. Profiling continues until the
241 /// TimingGuard returned from this call is dropped.
242 #[inline(always)]
243 pub fn generic_activity(&self, event_label: &'static str) -> TimingGuard<'_> {
244 self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
245 let event_label = profiler.get_or_alloc_cached_string(event_label);
246 let event_id = EventId::from_label(event_label);
247 TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
248 })
dfeec247
XL
249 }
250
e74abb32
XL
251 /// Start profiling a generic activity. Profiling continues until the
252 /// TimingGuard returned from this call is dropped.
253 #[inline(always)]
74b04a01
XL
254 pub fn generic_activity_with_arg<A>(
255 &self,
256 event_label: &'static str,
257 event_arg: A,
258 ) -> TimingGuard<'_>
259 where
260 A: Borrow<str> + Into<String>,
261 {
e74abb32 262 self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
74b04a01
XL
263 let builder = EventIdBuilder::new(&profiler.profiler);
264 let event_label = profiler.get_or_alloc_cached_string(event_label);
265 let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
266 let event_arg = profiler.get_or_alloc_cached_string(event_arg);
267 builder.from_label_and_arg(event_label, event_arg)
268 } else {
269 builder.from_label(event_label)
270 };
dfeec247 271 TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
e74abb32
XL
272 })
273 }
274
fc512014
XL
275 #[inline(always)]
276 pub fn generic_activity_with_args(
277 &self,
278 event_label: &'static str,
279 event_args: &[String],
280 ) -> TimingGuard<'_> {
281 self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
282 let builder = EventIdBuilder::new(&profiler.profiler);
283 let event_label = profiler.get_or_alloc_cached_string(event_label);
284 let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
285 let event_args: Vec<_> = event_args
286 .iter()
287 .map(|s| profiler.get_or_alloc_cached_string(&s[..]))
288 .collect();
289 builder.from_label_and_args(event_label, &event_args)
290 } else {
291 builder.from_label(event_label)
292 };
293 TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
294 })
295 }
296
e74abb32
XL
297 /// Start profiling a query provider. Profiling continues until the
298 /// TimingGuard returned from this call is dropped.
299 #[inline(always)]
dfeec247 300 pub fn query_provider(&self) -> TimingGuard<'_> {
e74abb32 301 self.exec(EventFilter::QUERY_PROVIDERS, |profiler| {
dfeec247 302 TimingGuard::start(profiler, profiler.query_event_kind, EventId::INVALID)
e74abb32
XL
303 })
304 }
305
306 /// Record a query in-memory cache hit.
307 #[inline(always)]
dfeec247 308 pub fn query_cache_hit(&self, query_invocation_id: QueryInvocationId) {
60c5eb7d 309 self.instant_query_event(
e74abb32 310 |profiler| profiler.query_cache_hit_event_kind,
dfeec247 311 query_invocation_id,
e74abb32 312 EventFilter::QUERY_CACHE_HITS,
e74abb32
XL
313 );
314 }
315
316 /// Start profiling a query being blocked on a concurrent execution.
317 /// Profiling continues until the TimingGuard returned from this call is
318 /// dropped.
319 #[inline(always)]
dfeec247 320 pub fn query_blocked(&self) -> TimingGuard<'_> {
e74abb32 321 self.exec(EventFilter::QUERY_BLOCKED, |profiler| {
dfeec247 322 TimingGuard::start(profiler, profiler.query_blocked_event_kind, EventId::INVALID)
e74abb32
XL
323 })
324 }
325
326 /// Start profiling how long it takes to load a query result from the
327 /// incremental compilation on-disk cache. Profiling continues until the
328 /// TimingGuard returned from this call is dropped.
329 #[inline(always)]
dfeec247 330 pub fn incr_cache_loading(&self) -> TimingGuard<'_> {
e74abb32 331 self.exec(EventFilter::INCR_CACHE_LOADS, |profiler| {
e74abb32
XL
332 TimingGuard::start(
333 profiler,
334 profiler.incremental_load_result_event_kind,
dfeec247 335 EventId::INVALID,
e74abb32
XL
336 )
337 })
338 }
339
340 #[inline(always)]
60c5eb7d 341 fn instant_query_event(
e74abb32
XL
342 &self,
343 event_kind: fn(&SelfProfiler) -> StringId,
dfeec247 344 query_invocation_id: QueryInvocationId,
e74abb32 345 event_filter: EventFilter,
e74abb32
XL
346 ) {
347 drop(self.exec(event_filter, |profiler| {
dfeec247 348 let event_id = StringId::new_virtual(query_invocation_id.0);
ba9703b0 349 let thread_id = std::thread::current().id().as_u64().get() as u32;
e74abb32 350
60c5eb7d 351 profiler.profiler.record_instant_event(
e74abb32 352 event_kind(profiler),
dfeec247 353 EventId::from_virtual(event_id),
e74abb32 354 thread_id,
e74abb32
XL
355 );
356
357 TimingGuard::none()
358 }));
359 }
60c5eb7d 360
dfeec247 361 pub fn with_profiler(&self, f: impl FnOnce(&SelfProfiler)) {
60c5eb7d
XL
362 if let Some(profiler) = &self.profiler {
363 f(&profiler)
364 }
365 }
dfeec247
XL
366
367 #[inline]
368 pub fn enabled(&self) -> bool {
369 self.profiler.is_some()
370 }
74b04a01
XL
371
372 #[inline]
373 pub fn llvm_recording_enabled(&self) -> bool {
374 self.event_filter_mask.contains(EventFilter::LLVM)
375 }
376 #[inline]
377 pub fn get_self_profiler(&self) -> Option<Arc<SelfProfiler>> {
378 self.profiler.clone()
379 }
e74abb32
XL
380}
381
532ac7d7 382pub struct SelfProfiler {
48663c56
XL
383 profiler: Profiler,
384 event_filter_mask: EventFilter,
dfeec247 385
74b04a01 386 string_cache: RwLock<FxHashMap<String, StringId>>,
dfeec247 387
48663c56
XL
388 query_event_kind: StringId,
389 generic_activity_event_kind: StringId,
390 incremental_load_result_event_kind: StringId,
391 query_blocked_event_kind: StringId,
392 query_cache_hit_event_kind: StringId,
b7449926
XL
393}
394
395impl SelfProfiler {
dc9dc135
XL
396 pub fn new(
397 output_directory: &Path,
398 crate_name: Option<&str>,
dfeec247 399 event_filters: &Option<Vec<String>>,
29967ef6 400 ) -> Result<SelfProfiler, Box<dyn Error + Send + Sync>> {
dc9dc135
XL
401 fs::create_dir_all(output_directory)?;
402
403 let crate_name = crate_name.unwrap_or("unknown-crate");
404 let filename = format!("{}-{}.rustc_profile", crate_name, process::id());
405 let path = output_directory.join(&filename);
406 let profiler = Profiler::new(&path)?;
48663c56
XL
407
408 let query_event_kind = profiler.alloc_string("Query");
409 let generic_activity_event_kind = profiler.alloc_string("GenericActivity");
410 let incremental_load_result_event_kind = profiler.alloc_string("IncrementalLoadResult");
411 let query_blocked_event_kind = profiler.alloc_string("QueryBlocked");
412 let query_cache_hit_event_kind = profiler.alloc_string("QueryCacheHit");
413
414 let mut event_filter_mask = EventFilter::empty();
415
416 if let Some(ref event_filters) = *event_filters {
417 let mut unknown_events = vec![];
418 for item in event_filters {
dfeec247
XL
419 if let Some(&(_, mask)) =
420 EVENT_FILTERS_BY_NAME.iter().find(|&(name, _)| name == item)
421 {
48663c56
XL
422 event_filter_mask |= mask;
423 } else {
424 unknown_events.push(item.clone());
425 }
426 }
427
428 // Warn about any unknown event names
74b04a01 429 if !unknown_events.is_empty() {
48663c56
XL
430 unknown_events.sort();
431 unknown_events.dedup();
432
dfeec247
XL
433 warn!(
434 "Unknown self-profiler events specified: {}. Available options are: {}.",
48663c56 435 unknown_events.join(", "),
dfeec247
XL
436 EVENT_FILTERS_BY_NAME
437 .iter()
438 .map(|&(name, _)| name.to_string())
439 .collect::<Vec<_>>()
440 .join(", ")
441 );
48663c56
XL
442 }
443 } else {
444 event_filter_mask = EventFilter::DEFAULT;
445 }
446
447 Ok(SelfProfiler {
448 profiler,
449 event_filter_mask,
dfeec247 450 string_cache: RwLock::new(FxHashMap::default()),
48663c56
XL
451 query_event_kind,
452 generic_activity_event_kind,
453 incremental_load_result_event_kind,
454 query_blocked_event_kind,
455 query_cache_hit_event_kind,
456 })
457 }
458
dfeec247
XL
459 /// Allocates a new string in the profiling data. Does not do any caching
460 /// or deduplication.
461 pub fn alloc_string<STR: SerializableString + ?Sized>(&self, s: &STR) -> StringId {
462 self.profiler.alloc_string(s)
463 }
464
465 /// Gets a `StringId` for the given string. This method makes sure that
466 /// any strings going through it will only be allocated once in the
467 /// profiling data.
74b04a01
XL
468 pub fn get_or_alloc_cached_string<A>(&self, s: A) -> StringId
469 where
470 A: Borrow<str> + Into<String>,
471 {
dfeec247
XL
472 // Only acquire a read-lock first since we assume that the string is
473 // already present in the common case.
474 {
475 let string_cache = self.string_cache.read();
476
74b04a01 477 if let Some(&id) = string_cache.get(s.borrow()) {
dfeec247
XL
478 return id;
479 }
480 }
481
482 let mut string_cache = self.string_cache.write();
483 // Check if the string has already been added in the small time window
484 // between dropping the read lock and acquiring the write lock.
74b04a01
XL
485 match string_cache.entry(s.into()) {
486 Entry::Occupied(e) => *e.get(),
487 Entry::Vacant(e) => {
488 let string_id = self.profiler.alloc_string(&e.key()[..]);
489 *e.insert(string_id)
490 }
491 }
dfeec247
XL
492 }
493
494 pub fn map_query_invocation_id_to_string(&self, from: QueryInvocationId, to: StringId) {
495 let from = StringId::new_virtual(from.0);
496 self.profiler.map_virtual_to_concrete_string(from, to);
497 }
b7449926 498
dfeec247
XL
499 pub fn bulk_map_query_invocation_id_to_single_string<I>(&self, from: I, to: StringId)
500 where
501 I: Iterator<Item = QueryInvocationId> + ExactSizeIterator,
502 {
503 let from = from.map(|qid| StringId::new_virtual(qid.0));
504 self.profiler.bulk_map_virtual_to_single_concrete_string(from, to);
48663c56
XL
505 }
506
dfeec247
XL
507 pub fn query_key_recording_enabled(&self) -> bool {
508 self.event_filter_mask.contains(EventFilter::QUERY_KEYS)
509 }
510
29967ef6 511 pub fn event_id_builder(&self) -> EventIdBuilder<'_> {
dfeec247 512 EventIdBuilder::new(&self.profiler)
b7449926 513 }
e74abb32 514}
b7449926 515
e74abb32 516#[must_use]
29967ef6 517pub struct TimingGuard<'a>(Option<measureme::TimingGuard<'a>>);
9fa01778 518
e74abb32 519impl<'a> TimingGuard<'a> {
9fa01778 520 #[inline]
e74abb32
XL
521 pub fn start(
522 profiler: &'a SelfProfiler,
523 event_kind: StringId,
dfeec247 524 event_id: EventId,
e74abb32 525 ) -> TimingGuard<'a> {
ba9703b0 526 let thread_id = std::thread::current().id().as_u64().get() as u32;
e74abb32 527 let raw_profiler = &profiler.profiler;
dfeec247
XL
528 let timing_guard =
529 raw_profiler.start_recording_interval_event(event_kind, event_id, thread_id);
e74abb32 530 TimingGuard(Some(timing_guard))
9fa01778
XL
531 }
532
dfeec247
XL
533 #[inline]
534 pub fn finish_with_query_invocation_id(self, query_invocation_id: QueryInvocationId) {
535 if let Some(guard) = self.0 {
74b04a01
XL
536 cold_path(|| {
537 let event_id = StringId::new_virtual(query_invocation_id.0);
538 let event_id = EventId::from_virtual(event_id);
539 guard.finish_with_override_event_id(event_id);
540 });
dfeec247
XL
541 }
542 }
543
532ac7d7 544 #[inline]
e74abb32
XL
545 pub fn none() -> TimingGuard<'a> {
546 TimingGuard(None)
b7449926 547 }
dfeec247
XL
548
549 #[inline(always)]
550 pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
551 let _timer = self;
552 f()
553 }
554}
555
556#[must_use]
557pub struct VerboseTimingGuard<'a> {
5869c6ff 558 start_and_message: Option<(Instant, Option<usize>, String)>,
dfeec247
XL
559 _guard: TimingGuard<'a>,
560}
561
562impl<'a> VerboseTimingGuard<'a> {
74b04a01 563 pub fn start(message: Option<String>, _guard: TimingGuard<'a>) -> Self {
5869c6ff
XL
564 VerboseTimingGuard {
565 _guard,
566 start_and_message: message.map(|msg| (Instant::now(), get_resident_set_size(), msg)),
567 }
dfeec247
XL
568 }
569
570 #[inline(always)]
571 pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
572 let _timer = self;
573 f()
574 }
575}
576
577impl Drop for VerboseTimingGuard<'_> {
578 fn drop(&mut self) {
5869c6ff
XL
579 if let Some((start_time, start_rss, ref message)) = self.start_and_message {
580 let end_rss = get_resident_set_size();
581 print_time_passes_entry(&message[..], start_time.elapsed(), start_rss, end_rss);
74b04a01 582 }
dfeec247
XL
583 }
584}
585
5869c6ff
XL
586pub fn print_time_passes_entry(
587 what: &str,
588 dur: Duration,
589 start_rss: Option<usize>,
590 end_rss: Option<usize>,
591) {
592 let rss_to_mb = |rss| (rss as f64 / 1_000_000.0).round() as usize;
593 let rss_change_to_mb = |rss| (rss as f64 / 1_000_000.0).round() as i128;
594
595 let mem_string = match (start_rss, end_rss) {
596 (Some(start_rss), Some(end_rss)) => {
597 let change_rss = end_rss as i128 - start_rss as i128;
598
599 format!(
600 "; rss: {:>4}MB -> {:>4}MB ({:>+5}MB)",
601 rss_to_mb(start_rss),
602 rss_to_mb(end_rss),
603 rss_change_to_mb(change_rss),
604 )
dfeec247 605 }
5869c6ff
XL
606 (Some(start_rss), None) => format!("; rss start: {:>4}MB", rss_to_mb(start_rss)),
607 (None, Some(end_rss)) => format!("; rss end: {:>4}MB", rss_to_mb(end_rss)),
608 (None, None) => String::new(),
dfeec247 609 };
5869c6ff 610
6a06907d 611 eprintln!("time: {:>7}{}\t{}", duration_to_secs_str(dur), mem_string, what);
dfeec247
XL
612}
613
614// Hack up our own formatting for the duration to make it easier for scripts
615// to parse (always use the same number of decimal places and the same unit).
616pub fn duration_to_secs_str(dur: std::time::Duration) -> String {
1b1a35ee 617 format!("{:.3}", dur.as_secs_f64())
dfeec247
XL
618}
619
620// Memory reporting
f9f354fc
XL
621cfg_if! {
622 if #[cfg(windows)] {
5869c6ff 623 pub fn get_resident_set_size() -> Option<usize> {
f9f354fc
XL
624 use std::mem::{self, MaybeUninit};
625 use winapi::shared::minwindef::DWORD;
626 use winapi::um::processthreadsapi::GetCurrentProcess;
627 use winapi::um::psapi::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
628
629 let mut pmc = MaybeUninit::<PROCESS_MEMORY_COUNTERS>::uninit();
630 match unsafe {
631 GetProcessMemoryInfo(GetCurrentProcess(), pmc.as_mut_ptr(), mem::size_of_val(&pmc) as DWORD)
632 } {
633 0 => None,
634 _ => {
635 let pmc = unsafe { pmc.assume_init() };
636 Some(pmc.WorkingSetSize as usize)
637 }
638 }
639 }
640 } else if #[cfg(unix)] {
5869c6ff 641 pub fn get_resident_set_size() -> Option<usize> {
f9f354fc
XL
642 let field = 1;
643 let contents = fs::read("/proc/self/statm").ok()?;
644 let contents = String::from_utf8(contents).ok()?;
645 let s = contents.split_whitespace().nth(field)?;
646 let npages = s.parse::<usize>().ok()?;
647 Some(npages * 4096)
648 }
649 } else {
5869c6ff 650 pub fn get_resident_set_size() -> Option<usize> {
f9f354fc 651 None
dfeec247
XL
652 }
653 }
b7449926 654}