1use std::borrow::Borrow;
85use std::collections::hash_map::Entry;
86use std::error::Error;
87use std::fmt::Display;
88use std::intrinsics::unlikely;
89use std::path::Path;
90use std::sync::Arc;
91use std::sync::atomic::Ordering;
92use std::time::{Duration, Instant};
93use std::{fs, process};
94
95pub use measureme::EventId;
96use measureme::{EventIdBuilder, Profiler, SerializableString, StringId};
97use parking_lot::RwLock;
98use smallvec::SmallVec;
99use tracing::warn;
100
101use crate::fx::FxHashMap;
102use crate::outline;
103use crate::sync::AtomicU64;
104
105bitflags::bitflags! {
106    #[derive(Clone, Copy)]
107    struct EventFilter: u16 {
108        const GENERIC_ACTIVITIES  = 1 << 0;
109        const QUERY_PROVIDERS     = 1 << 1;
110        const QUERY_CACHE_HITS    = 1 << 2;
113        const QUERY_BLOCKED       = 1 << 3;
114        const INCR_CACHE_LOADS    = 1 << 4;
115
116        const QUERY_KEYS          = 1 << 5;
117        const FUNCTION_ARGS       = 1 << 6;
118        const LLVM                = 1 << 7;
119        const INCR_RESULT_HASHING = 1 << 8;
120        const ARTIFACT_SIZES      = 1 << 9;
121        const QUERY_CACHE_HIT_COUNTS  = 1 << 10;
123
124        const DEFAULT = Self::GENERIC_ACTIVITIES.bits() |
125                        Self::QUERY_PROVIDERS.bits() |
126                        Self::QUERY_BLOCKED.bits() |
127                        Self::INCR_CACHE_LOADS.bits() |
128                        Self::INCR_RESULT_HASHING.bits() |
129                        Self::ARTIFACT_SIZES.bits() |
130                        Self::QUERY_CACHE_HIT_COUNTS.bits();
131
132        const ARGS = Self::QUERY_KEYS.bits() | Self::FUNCTION_ARGS.bits();
133        const QUERY_CACHE_HIT_COMBINED = Self::QUERY_CACHE_HITS.bits() | Self::QUERY_CACHE_HIT_COUNTS.bits();
134    }
135}
136
137const EVENT_FILTERS_BY_NAME: &[(&str, EventFilter)] = &[
139    ("none", EventFilter::empty()),
140    ("all", EventFilter::all()),
141    ("default", EventFilter::DEFAULT),
142    ("generic-activity", EventFilter::GENERIC_ACTIVITIES),
143    ("query-provider", EventFilter::QUERY_PROVIDERS),
144    ("query-cache-hit", EventFilter::QUERY_CACHE_HITS),
145    ("query-cache-hit-count", EventFilter::QUERY_CACHE_HIT_COUNTS),
146    ("query-blocked", EventFilter::QUERY_BLOCKED),
147    ("incr-cache-load", EventFilter::INCR_CACHE_LOADS),
148    ("query-keys", EventFilter::QUERY_KEYS),
149    ("function-args", EventFilter::FUNCTION_ARGS),
150    ("args", EventFilter::ARGS),
151    ("llvm", EventFilter::LLVM),
152    ("incr-result-hashing", EventFilter::INCR_RESULT_HASHING),
153    ("artifact-sizes", EventFilter::ARTIFACT_SIZES),
154];
155
156pub struct QueryInvocationId(pub u32);
158
159#[derive(Clone, Copy, PartialEq, Hash, Debug)]
161pub enum TimePassesFormat {
162    Text,
164    Json,
166}
167
168#[derive(Clone)]
171pub struct SelfProfilerRef {
172    profiler: Option<Arc<SelfProfiler>>,
175
176    event_filter_mask: EventFilter,
180
181    print_verbose_generic_activities: Option<TimePassesFormat>,
183}
184
185impl SelfProfilerRef {
186    pub fn new(
187        profiler: Option<Arc<SelfProfiler>>,
188        print_verbose_generic_activities: Option<TimePassesFormat>,
189    ) -> SelfProfilerRef {
190        let event_filter_mask =
193            profiler.as_ref().map_or(EventFilter::empty(), |p| p.event_filter_mask);
194
195        SelfProfilerRef { profiler, event_filter_mask, print_verbose_generic_activities }
196    }
197
198    #[inline(always)]
204    fn exec<F>(&self, event_filter: EventFilter, f: F) -> TimingGuard<'_>
205    where
206        F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
207    {
208        #[inline(never)]
209        #[cold]
210        fn cold_call<F>(profiler_ref: &SelfProfilerRef, f: F) -> TimingGuard<'_>
211        where
212            F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
213        {
214            let profiler = profiler_ref.profiler.as_ref().unwrap();
215            f(profiler)
216        }
217
218        if self.event_filter_mask.contains(event_filter) {
219            cold_call(self, f)
220        } else {
221            TimingGuard::none()
222        }
223    }
224
225    pub fn verbose_generic_activity(&self, event_label: &'static str) -> VerboseTimingGuard<'_> {
230        let message_and_format =
231            self.print_verbose_generic_activities.map(|format| (event_label.to_owned(), format));
232
233        VerboseTimingGuard::start(message_and_format, self.generic_activity(event_label))
234    }
235
236    pub fn verbose_generic_activity_with_arg<A>(
238        &self,
239        event_label: &'static str,
240        event_arg: A,
241    ) -> VerboseTimingGuard<'_>
242    where
243        A: Borrow<str> + Into<String>,
244    {
245        let message_and_format = self
246            .print_verbose_generic_activities
247            .map(|format| (format!("{}({})", event_label, event_arg.borrow()), format));
248
249        VerboseTimingGuard::start(
250            message_and_format,
251            self.generic_activity_with_arg(event_label, event_arg),
252        )
253    }
254
255    #[inline(always)]
258    pub fn generic_activity(&self, event_label: &'static str) -> TimingGuard<'_> {
259        self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
260            let event_label = profiler.get_or_alloc_cached_string(event_label);
261            let event_id = EventId::from_label(event_label);
262            TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
263        })
264    }
265
266    #[inline(always)]
269    pub fn generic_activity_with_event_id(&self, event_id: EventId) -> TimingGuard<'_> {
270        self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
271            TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
272        })
273    }
274
275    #[inline(always)]
278    pub fn generic_activity_with_arg<A>(
279        &self,
280        event_label: &'static str,
281        event_arg: A,
282    ) -> TimingGuard<'_>
283    where
284        A: Borrow<str> + Into<String>,
285    {
286        self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
287            let builder = EventIdBuilder::new(&profiler.profiler);
288            let event_label = profiler.get_or_alloc_cached_string(event_label);
289            let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
290                let event_arg = profiler.get_or_alloc_cached_string(event_arg);
291                builder.from_label_and_arg(event_label, event_arg)
292            } else {
293                builder.from_label(event_label)
294            };
295            TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
296        })
297    }
298
299    #[inline(always)]
320    pub fn generic_activity_with_arg_recorder<F>(
321        &self,
322        event_label: &'static str,
323        mut f: F,
324    ) -> TimingGuard<'_>
325    where
326        F: FnMut(&mut EventArgRecorder<'_>),
327    {
328        self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
330            let builder = EventIdBuilder::new(&profiler.profiler);
331            let event_label = profiler.get_or_alloc_cached_string(event_label);
332
333            let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
336                let mut recorder = EventArgRecorder { profiler, args: SmallVec::new() };
339                f(&mut recorder);
340
341                if recorder.args.is_empty() {
345                    panic!(
346                        "The closure passed to `generic_activity_with_arg_recorder` needs to \
347                         record at least one argument"
348                    );
349                }
350
351                builder.from_label_and_args(event_label, &recorder.args)
352            } else {
353                builder.from_label(event_label)
354            };
355            TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
356        })
357    }
358
359    #[inline(always)]
364    pub fn artifact_size<A>(&self, artifact_kind: &str, artifact_name: A, size: u64)
365    where
366        A: Borrow<str> + Into<String>,
367    {
368        drop(self.exec(EventFilter::ARTIFACT_SIZES, |profiler| {
369            let builder = EventIdBuilder::new(&profiler.profiler);
370            let event_label = profiler.get_or_alloc_cached_string(artifact_kind);
371            let event_arg = profiler.get_or_alloc_cached_string(artifact_name);
372            let event_id = builder.from_label_and_arg(event_label, event_arg);
373            let thread_id = get_thread_id();
374
375            profiler.profiler.record_integer_event(
376                profiler.artifact_size_event_kind,
377                event_id,
378                thread_id,
379                size,
380            );
381
382            TimingGuard::none()
383        }))
384    }
385
386    #[inline(always)]
387    pub fn generic_activity_with_args(
388        &self,
389        event_label: &'static str,
390        event_args: &[String],
391    ) -> TimingGuard<'_> {
392        self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
393            let builder = EventIdBuilder::new(&profiler.profiler);
394            let event_label = profiler.get_or_alloc_cached_string(event_label);
395            let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
396                let event_args: Vec<_> = event_args
397                    .iter()
398                    .map(|s| profiler.get_or_alloc_cached_string(&s[..]))
399                    .collect();
400                builder.from_label_and_args(event_label, &event_args)
401            } else {
402                builder.from_label(event_label)
403            };
404            TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
405        })
406    }
407
408    #[inline(always)]
411    pub fn query_provider(&self) -> TimingGuard<'_> {
412        self.exec(EventFilter::QUERY_PROVIDERS, |profiler| {
413            TimingGuard::start(profiler, profiler.query_event_kind, EventId::INVALID)
414        })
415    }
416
417    #[inline(always)]
419    pub fn query_cache_hit(&self, query_invocation_id: QueryInvocationId) {
420        #[inline(never)]
421        #[cold]
422        fn cold_call(profiler_ref: &SelfProfilerRef, query_invocation_id: QueryInvocationId) {
423            if profiler_ref.event_filter_mask.contains(EventFilter::QUERY_CACHE_HIT_COUNTS) {
424                profiler_ref
425                    .profiler
426                    .as_ref()
427                    .unwrap()
428                    .increment_query_cache_hit_counters(QueryInvocationId(query_invocation_id.0));
429            }
430            if unlikely(profiler_ref.event_filter_mask.contains(EventFilter::QUERY_CACHE_HITS)) {
431                profiler_ref.instant_query_event(
432                    |profiler| profiler.query_cache_hit_event_kind,
433                    query_invocation_id,
434                );
435            }
436        }
437
438        if unlikely(self.event_filter_mask.intersects(EventFilter::QUERY_CACHE_HIT_COMBINED)) {
441            cold_call(self, query_invocation_id);
442        }
443    }
444
445    #[inline(always)]
449    pub fn query_blocked(&self) -> TimingGuard<'_> {
450        self.exec(EventFilter::QUERY_BLOCKED, |profiler| {
451            TimingGuard::start(profiler, profiler.query_blocked_event_kind, EventId::INVALID)
452        })
453    }
454
455    #[inline(always)]
459    pub fn incr_cache_loading(&self) -> TimingGuard<'_> {
460        self.exec(EventFilter::INCR_CACHE_LOADS, |profiler| {
461            TimingGuard::start(
462                profiler,
463                profiler.incremental_load_result_event_kind,
464                EventId::INVALID,
465            )
466        })
467    }
468
469    #[inline(always)]
472    pub fn incr_result_hashing(&self) -> TimingGuard<'_> {
473        self.exec(EventFilter::INCR_RESULT_HASHING, |profiler| {
474            TimingGuard::start(
475                profiler,
476                profiler.incremental_result_hashing_event_kind,
477                EventId::INVALID,
478            )
479        })
480    }
481
482    #[inline(always)]
483    fn instant_query_event(
484        &self,
485        event_kind: fn(&SelfProfiler) -> StringId,
486        query_invocation_id: QueryInvocationId,
487    ) {
488        let event_id = StringId::new_virtual(query_invocation_id.0);
489        let thread_id = get_thread_id();
490        let profiler = self.profiler.as_ref().unwrap();
491        profiler.profiler.record_instant_event(
492            event_kind(profiler),
493            EventId::from_virtual(event_id),
494            thread_id,
495        );
496    }
497
498    pub fn with_profiler(&self, f: impl FnOnce(&SelfProfiler)) {
499        if let Some(profiler) = &self.profiler {
500            f(profiler)
501        }
502    }
503
504    pub fn get_or_alloc_cached_string(&self, s: &str) -> Option<StringId> {
509        self.profiler.as_ref().map(|p| p.get_or_alloc_cached_string(s))
510    }
511
512    pub fn store_query_cache_hits(&self) {
519        if self.event_filter_mask.contains(EventFilter::QUERY_CACHE_HIT_COUNTS) {
520            let profiler = self.profiler.as_ref().unwrap();
521            let query_hits = profiler.query_hits.read();
522            let builder = EventIdBuilder::new(&profiler.profiler);
523            let thread_id = get_thread_id();
524            for (query_invocation, hit_count) in query_hits.iter().enumerate() {
525                let hit_count = hit_count.load(Ordering::Relaxed);
526                if hit_count > 0 {
528                    let event_id =
529                        builder.from_label(StringId::new_virtual(query_invocation as u64));
530                    profiler.profiler.record_integer_event(
531                        profiler.query_cache_hit_count_event_kind,
532                        event_id,
533                        thread_id,
534                        hit_count,
535                    );
536                }
537            }
538        }
539    }
540
541    #[inline]
542    pub fn enabled(&self) -> bool {
543        self.profiler.is_some()
544    }
545
546    #[inline]
547    pub fn llvm_recording_enabled(&self) -> bool {
548        self.event_filter_mask.contains(EventFilter::LLVM)
549    }
550    #[inline]
551    pub fn get_self_profiler(&self) -> Option<Arc<SelfProfiler>> {
552        self.profiler.clone()
553    }
554
555    pub fn is_args_recording_enabled(&self) -> bool {
557        self.enabled() && self.event_filter_mask.intersects(EventFilter::ARGS)
558    }
559}
560
561pub struct EventArgRecorder<'p> {
564    profiler: &'p SelfProfiler,
566
567    args: SmallVec<[StringId; 2]>,
572}
573
574impl EventArgRecorder<'_> {
575    pub fn record_arg<A>(&mut self, event_arg: A)
580    where
581        A: Borrow<str> + Into<String>,
582    {
583        let event_arg = self.profiler.get_or_alloc_cached_string(event_arg);
584        self.args.push(event_arg);
585    }
586}
587
588pub struct SelfProfiler {
589    profiler: Profiler,
590    event_filter_mask: EventFilter,
591
592    string_cache: RwLock<FxHashMap<String, StringId>>,
593
594    query_hits: RwLock<Vec<AtomicU64>>,
606
607    query_event_kind: StringId,
608    generic_activity_event_kind: StringId,
609    incremental_load_result_event_kind: StringId,
610    incremental_result_hashing_event_kind: StringId,
611    query_blocked_event_kind: StringId,
612    query_cache_hit_event_kind: StringId,
613    artifact_size_event_kind: StringId,
614    query_cache_hit_count_event_kind: StringId,
616}
617
618impl SelfProfiler {
619    pub fn new(
620        output_directory: &Path,
621        crate_name: Option<&str>,
622        event_filters: Option<&[String]>,
623        counter_name: &str,
624    ) -> Result<SelfProfiler, Box<dyn Error + Send + Sync>> {
625        fs::create_dir_all(output_directory)?;
626
627        let crate_name = crate_name.unwrap_or("unknown-crate");
628        let pid: u32 = process::id();
632        let filename = format!("{crate_name}-{pid:07}.rustc_profile");
633        let path = output_directory.join(filename);
634        let profiler =
635            Profiler::with_counter(&path, measureme::counters::Counter::by_name(counter_name)?)?;
636
637        let query_event_kind = profiler.alloc_string("Query");
638        let generic_activity_event_kind = profiler.alloc_string("GenericActivity");
639        let incremental_load_result_event_kind = profiler.alloc_string("IncrementalLoadResult");
640        let incremental_result_hashing_event_kind =
641            profiler.alloc_string("IncrementalResultHashing");
642        let query_blocked_event_kind = profiler.alloc_string("QueryBlocked");
643        let query_cache_hit_event_kind = profiler.alloc_string("QueryCacheHit");
644        let artifact_size_event_kind = profiler.alloc_string("ArtifactSize");
645        let query_cache_hit_count_event_kind = profiler.alloc_string("QueryCacheHitCount");
646
647        let mut event_filter_mask = EventFilter::empty();
648
649        if let Some(event_filters) = event_filters {
650            let mut unknown_events = vec![];
651            for item in event_filters {
652                if let Some(&(_, mask)) =
653                    EVENT_FILTERS_BY_NAME.iter().find(|&(name, _)| name == item)
654                {
655                    event_filter_mask |= mask;
656                } else {
657                    unknown_events.push(item.clone());
658                }
659            }
660
661            if !unknown_events.is_empty() {
663                unknown_events.sort();
664                unknown_events.dedup();
665
666                warn!(
667                    "Unknown self-profiler events specified: {}. Available options are: {}.",
668                    unknown_events.join(", "),
669                    EVENT_FILTERS_BY_NAME
670                        .iter()
671                        .map(|&(name, _)| name.to_string())
672                        .collect::<Vec<_>>()
673                        .join(", ")
674                );
675            }
676        } else {
677            event_filter_mask = EventFilter::DEFAULT;
678        }
679
680        Ok(SelfProfiler {
681            profiler,
682            event_filter_mask,
683            string_cache: RwLock::new(FxHashMap::default()),
684            query_event_kind,
685            generic_activity_event_kind,
686            incremental_load_result_event_kind,
687            incremental_result_hashing_event_kind,
688            query_blocked_event_kind,
689            query_cache_hit_event_kind,
690            artifact_size_event_kind,
691            query_cache_hit_count_event_kind,
692            query_hits: Default::default(),
693        })
694    }
695
696    pub fn alloc_string<STR: SerializableString + ?Sized>(&self, s: &STR) -> StringId {
699        self.profiler.alloc_string(s)
700    }
701
702    pub fn increment_query_cache_hit_counters(&self, id: QueryInvocationId) {
704        let mut guard = self.query_hits.upgradable_read();
707        let query_hits = &guard;
708        let index = id.0 as usize;
709        if index < query_hits.len() {
710            query_hits[index].fetch_add(1, Ordering::Relaxed);
712        } else {
713            guard.with_upgraded(|vec| {
715                vec.resize_with(index + 1, || AtomicU64::new(0));
716                vec[index] = AtomicU64::from(1);
717            });
718        }
719    }
720
721    pub fn get_or_alloc_cached_string<A>(&self, s: A) -> StringId
725    where
726        A: Borrow<str> + Into<String>,
727    {
728        {
731            let string_cache = self.string_cache.read();
732
733            if let Some(&id) = string_cache.get(s.borrow()) {
734                return id;
735            }
736        }
737
738        let mut string_cache = self.string_cache.write();
739        match string_cache.entry(s.into()) {
742            Entry::Occupied(e) => *e.get(),
743            Entry::Vacant(e) => {
744                let string_id = self.profiler.alloc_string(&e.key()[..]);
745                *e.insert(string_id)
746            }
747        }
748    }
749
750    pub fn map_query_invocation_id_to_string(&self, from: QueryInvocationId, to: StringId) {
751        let from = StringId::new_virtual(from.0);
752        self.profiler.map_virtual_to_concrete_string(from, to);
753    }
754
755    pub fn bulk_map_query_invocation_id_to_single_string<I>(&self, from: I, to: StringId)
756    where
757        I: Iterator<Item = QueryInvocationId> + ExactSizeIterator,
758    {
759        let from = from.map(|qid| StringId::new_virtual(qid.0));
760        self.profiler.bulk_map_virtual_to_single_concrete_string(from, to);
761    }
762
763    pub fn query_key_recording_enabled(&self) -> bool {
764        self.event_filter_mask.contains(EventFilter::QUERY_KEYS)
765    }
766
767    pub fn event_id_builder(&self) -> EventIdBuilder<'_> {
768        EventIdBuilder::new(&self.profiler)
769    }
770}
771
772#[must_use]
773pub struct TimingGuard<'a>(Option<measureme::TimingGuard<'a>>);
774
775impl<'a> TimingGuard<'a> {
776    #[inline]
777    pub fn start(
778        profiler: &'a SelfProfiler,
779        event_kind: StringId,
780        event_id: EventId,
781    ) -> TimingGuard<'a> {
782        let thread_id = get_thread_id();
783        let raw_profiler = &profiler.profiler;
784        let timing_guard =
785            raw_profiler.start_recording_interval_event(event_kind, event_id, thread_id);
786        TimingGuard(Some(timing_guard))
787    }
788
789    #[inline]
790    pub fn finish_with_query_invocation_id(self, query_invocation_id: QueryInvocationId) {
791        if let Some(guard) = self.0 {
792            outline(|| {
793                let event_id = StringId::new_virtual(query_invocation_id.0);
794                let event_id = EventId::from_virtual(event_id);
795                guard.finish_with_override_event_id(event_id);
796            });
797        }
798    }
799
800    #[inline]
801    pub fn none() -> TimingGuard<'a> {
802        TimingGuard(None)
803    }
804
805    #[inline(always)]
806    pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
807        let _timer = self;
808        f()
809    }
810}
811
812struct VerboseInfo {
813    start_time: Instant,
814    start_rss: Option<usize>,
815    message: String,
816    format: TimePassesFormat,
817}
818
819#[must_use]
820pub struct VerboseTimingGuard<'a> {
821    info: Option<VerboseInfo>,
822    _guard: TimingGuard<'a>,
823}
824
825impl<'a> VerboseTimingGuard<'a> {
826    pub fn start(
827        message_and_format: Option<(String, TimePassesFormat)>,
828        _guard: TimingGuard<'a>,
829    ) -> Self {
830        VerboseTimingGuard {
831            _guard,
832            info: message_and_format.map(|(message, format)| VerboseInfo {
833                start_time: Instant::now(),
834                start_rss: get_resident_set_size(),
835                message,
836                format,
837            }),
838        }
839    }
840
841    #[inline(always)]
842    pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
843        let _timer = self;
844        f()
845    }
846}
847
848impl Drop for VerboseTimingGuard<'_> {
849    fn drop(&mut self) {
850        if let Some(info) = &self.info {
851            let end_rss = get_resident_set_size();
852            let dur = info.start_time.elapsed();
853            print_time_passes_entry(&info.message, dur, info.start_rss, end_rss, info.format);
854        }
855    }
856}
857
858struct JsonTimePassesEntry<'a> {
859    pass: &'a str,
860    time: f64,
861    start_rss: Option<usize>,
862    end_rss: Option<usize>,
863}
864
865impl Display for JsonTimePassesEntry<'_> {
866    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
867        let Self { pass: what, time, start_rss, end_rss } = self;
868        write!(f, r#"{{"pass":"{what}","time":{time},"rss_start":"#).unwrap();
869        match start_rss {
870            Some(rss) => write!(f, "{rss}")?,
871            None => write!(f, "null")?,
872        }
873        write!(f, r#","rss_end":"#)?;
874        match end_rss {
875            Some(rss) => write!(f, "{rss}")?,
876            None => write!(f, "null")?,
877        }
878        write!(f, "}}")?;
879        Ok(())
880    }
881}
882
883pub fn print_time_passes_entry(
884    what: &str,
885    dur: Duration,
886    start_rss: Option<usize>,
887    end_rss: Option<usize>,
888    format: TimePassesFormat,
889) {
890    match format {
891        TimePassesFormat::Json => {
892            let entry =
893                JsonTimePassesEntry { pass: what, time: dur.as_secs_f64(), start_rss, end_rss };
894
895            eprintln!(r#"time: {entry}"#);
896            return;
897        }
898        TimePassesFormat::Text => (),
899    }
900
901    let is_notable = || {
904        if dur.as_millis() > 5 {
905            return true;
906        }
907
908        if let (Some(start_rss), Some(end_rss)) = (start_rss, end_rss) {
909            let change_rss = end_rss.abs_diff(start_rss);
910            if change_rss > 0 {
911                return true;
912            }
913        }
914
915        false
916    };
917    if !is_notable() {
918        return;
919    }
920
921    let rss_to_mb = |rss| (rss as f64 / 1_000_000.0).round() as usize;
922    let rss_change_to_mb = |rss| (rss as f64 / 1_000_000.0).round() as i128;
923
924    let mem_string = match (start_rss, end_rss) {
925        (Some(start_rss), Some(end_rss)) => {
926            let change_rss = end_rss as i128 - start_rss as i128;
927
928            format!(
929                "; rss: {:>4}MB -> {:>4}MB ({:>+5}MB)",
930                rss_to_mb(start_rss),
931                rss_to_mb(end_rss),
932                rss_change_to_mb(change_rss),
933            )
934        }
935        (Some(start_rss), None) => format!("; rss start: {:>4}MB", rss_to_mb(start_rss)),
936        (None, Some(end_rss)) => format!("; rss end: {:>4}MB", rss_to_mb(end_rss)),
937        (None, None) => String::new(),
938    };
939
940    eprintln!("time: {:>7}{}\t{}", duration_to_secs_str(dur), mem_string, what);
941}
942
943pub fn duration_to_secs_str(dur: std::time::Duration) -> String {
946    format!("{:.3}", dur.as_secs_f64())
947}
948
949fn get_thread_id() -> u32 {
950    std::thread::current().id().as_u64().get() as u32
951}
952
953cfg_select! {
955    windows => {
956        pub fn get_resident_set_size() -> Option<usize> {
957            use windows::{
958                Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
959                Win32::System::Threading::GetCurrentProcess,
960            };
961
962            let mut pmc = PROCESS_MEMORY_COUNTERS::default();
963            let pmc_size = size_of_val(&pmc);
964            unsafe {
965                K32GetProcessMemoryInfo(
966                    GetCurrentProcess(),
967                    &mut pmc,
968                    pmc_size as u32,
969                )
970            }
971            .ok()
972            .ok()?;
973
974            Some(pmc.WorkingSetSize)
975        }
976    }
977    target_os = "macos" => {
978        pub fn get_resident_set_size() -> Option<usize> {
979            use libc::{c_int, c_void, getpid, proc_pidinfo, proc_taskinfo, PROC_PIDTASKINFO};
980            use std::mem;
981            const PROC_TASKINFO_SIZE: c_int = size_of::<proc_taskinfo>() as c_int;
982
983            unsafe {
984                let mut info: proc_taskinfo = mem::zeroed();
985                let info_ptr = &mut info as *mut proc_taskinfo as *mut c_void;
986                let pid = getpid() as c_int;
987                let ret = proc_pidinfo(pid, PROC_PIDTASKINFO, 0, info_ptr, PROC_TASKINFO_SIZE);
988                if ret == PROC_TASKINFO_SIZE {
989                    Some(info.pti_resident_size as usize)
990                } else {
991                    None
992                }
993            }
994        }
995    }
996    unix => {
997        pub fn get_resident_set_size() -> Option<usize> {
998            let field = 1;
999            let contents = fs::read("/proc/self/statm").ok()?;
1000            let contents = String::from_utf8(contents).ok()?;
1001            let s = contents.split_whitespace().nth(field)?;
1002            let npages = s.parse::<usize>().ok()?;
1003            Some(npages * 4096)
1004        }
1005    }
1006    _ => {
1007        pub fn get_resident_set_size() -> Option<usize> {
1008            None
1009        }
1010    }
1011}
1012
1013#[cfg(test)]
1014mod tests;