1use crate::counters::Counter;
2use crate::file_header::{write_file_header, FILE_MAGIC_EVENT_STREAM, FILE_MAGIC_TOP_LEVEL};
3use crate::raw_event::RawEvent;
4use crate::serialization::{PageTag, SerializationSink, SerializationSinkBuilder};
5use crate::stringtable::{SerializableString, StringId, StringTableBuilder};
6use crate::{event_id::EventId, file_header::FILE_EXTENSION};
7use std::error::Error;
8use std::fs;
9use std::path::Path;
10use std::sync::Arc;
11
12pub struct Profiler {
13 event_sink: Arc<SerializationSink>,
14 string_table: StringTableBuilder,
15 counter: Counter,
16}
17
18impl Profiler {
19 pub fn new<P: AsRef<Path>>(path_stem: P) -> Result<Profiler, Box<dyn Error + Send + Sync>> {
20 Self::with_counter(
21 path_stem,
22 Counter::WallTime(crate::counters::WallTime::new()),
23 )
24 }
25
26 pub fn with_counter<P: AsRef<Path>>(
27 path_stem: P,
28 counter: Counter,
29 ) -> Result<Profiler, Box<dyn Error + Send + Sync>> {
30 let path = path_stem.as_ref().with_extension(FILE_EXTENSION);
31
32 fs::create_dir_all(path.parent().unwrap())?;
33 let mut file = fs::File::create(path)?;
34
35 // The first thing in the file must be the top-level file header.
36 write_file_header(&mut file, FILE_MAGIC_TOP_LEVEL)?;
37
38 let sink_builder = SerializationSinkBuilder::new_from_file(file)?;
39 let event_sink = Arc::new(sink_builder.new_sink(PageTag::Events));
40
41 // The first thing in every stream we generate must be the stream header.
42 write_file_header(&mut event_sink.as_std_write(), FILE_MAGIC_EVENT_STREAM)?;
43
44 let string_table = StringTableBuilder::new(
45 Arc::new(sink_builder.new_sink(PageTag::StringData)),
46 Arc::new(sink_builder.new_sink(PageTag::StringIndex)),
47 )?;
48
49 let profiler = Profiler {
50 event_sink,
51 string_table,
52 counter,
53 };
54
55 let mut args = String::new();
56 for arg in std::env::args() {
57 args.push_str(&arg.escape_default().to_string());
58 args.push(' ');
59 }
60
61 profiler.string_table.alloc_metadata(&*format!(
62 r#"{{ "start_time": {}, "process_id": {}, "cmd": "{}", "counter": {} }}"#,
63 std::time::SystemTime::now()
64 .duration_since(std::time::UNIX_EPOCH)
65 .unwrap()
66 .as_nanos(),
67 std::process::id(),
68 args,
69 profiler.counter.describe_as_json(),
70 ));
71
72 Ok(profiler)
73 }
74
75 #[inline(always)]
76 pub fn map_virtual_to_concrete_string(&self, virtual_id: StringId, concrete_id: StringId) {
77 self.string_table
78 .map_virtual_to_concrete_string(virtual_id, concrete_id);
79 }
80
81 #[inline(always)]
82 pub fn bulk_map_virtual_to_single_concrete_string<I>(
83 &self,
84 virtual_ids: I,
85 concrete_id: StringId,
86 ) where
87 I: Iterator<Item = StringId> + ExactSizeIterator,
88 {
89 self.string_table
90 .bulk_map_virtual_to_single_concrete_string(virtual_ids, concrete_id);
91 }
92
93 #[inline(always)]
94 pub fn alloc_string<STR: SerializableString + ?Sized>(&self, s: &STR) -> StringId {
95 self.string_table.alloc(s)
96 }
97
98 /// Records an event with the given parameters. The event time is computed
99 /// automatically.
100 pub fn record_instant_event(&self, event_kind: StringId, event_id: EventId, thread_id: u32) {
101 let raw_event =
102 RawEvent::new_instant(event_kind, event_id, thread_id, self.counter.since_start());
103
104 self.record_raw_event(&raw_event);
105 }
106
107 /// Records an event with the given parameters. The event time is computed
108 /// automatically.
109 pub fn record_integer_event(
110 &self,
111 event_kind: StringId,
112 event_id: EventId,
113 thread_id: u32,
114 value: u64,
115 ) {
116 let raw_event = RawEvent::new_integer(event_kind, event_id, thread_id, value);
117 self.record_raw_event(&raw_event);
118 }
119
120 /// Creates a "start" event and returns a `TimingGuard` that will create
121 /// the corresponding "end" event when it is dropped.
122 #[inline]
123 pub fn start_recording_interval_event<'a>(
124 &'a self,
125 event_kind: StringId,
126 event_id: EventId,
127 thread_id: u32,
128 ) -> TimingGuard<'a> {
129 TimingGuard {
130 profiler: self,
131 event_id,
132 event_kind,
133 thread_id,
134 start_count: self.counter.since_start(),
135 }
136 }
137
138 /// Creates a "start" event and returns a `DetachedTiming`.
139 /// To create the corresponding "event" event, you must call
140 /// `finish_recording_internal_event` with the returned
141 /// `DetachedTiming`.
142 /// Since `DetachedTiming` does not capture the lifetime of `&self`,
143 /// this method can sometimes be more convenient than
144 /// `start_recording_interval_event` - e.g. it can be stored
145 /// in a struct without the need to add a lifetime parameter.
146 #[inline]
147 pub fn start_recording_interval_event_detached(
148 &self,
149 event_kind: StringId,
150 event_id: EventId,
151 thread_id: u32,
152 ) -> DetachedTiming {
153 DetachedTiming {
154 event_id,
155 event_kind,
156 thread_id,
157 start_count: self.counter.since_start(),
158 }
159 }
160
161 /// Creates the corresponding "end" event for
162 /// the "start" event represented by `timing`. You
163 /// must have obtained `timing` from the same `Profiler`
164 pub fn finish_recording_interval_event(&self, timing: DetachedTiming) {
165 drop(TimingGuard {
166 profiler: self,
167 event_id: timing.event_id,
168 event_kind: timing.event_kind,
169 thread_id: timing.thread_id,
170 start_count: timing.start_count,
171 });
172 }
173
174 fn record_raw_event(&self, raw_event: &RawEvent) {
175 self.event_sink
176 .write_atomic(std::mem::size_of::<RawEvent>(), |bytes| {
177 raw_event.serialize(bytes);
178 });
179 }
180}
181
182/// Created by `Profiler::start_recording_interval_event_detached`.
183/// Must be passed to `finish_recording_interval_event` to record an
184/// "end" event.
185#[must_use]
186pub struct DetachedTiming {
187 event_id: EventId,
188 event_kind: StringId,
189 thread_id: u32,
190 start_count: u64,
191}
192
193/// When dropped, this `TimingGuard` will record an "end" event in the
194/// `Profiler` it was created by.
195#[must_use]
196pub struct TimingGuard<'a> {
197 profiler: &'a Profiler,
198 event_id: EventId,
199 event_kind: StringId,
200 thread_id: u32,
201 start_count: u64,
202}
203
204impl<'a> Drop for TimingGuard<'a> {
205 #[inline]
206 fn drop(&mut self) {
207 let raw_event: RawEvent = RawEvent::new_interval(
208 self.event_kind,
209 self.event_id,
210 self.thread_id,
211 self.start_count,
212 self.profiler.counter.since_start(),
213 );
214
215 self.profiler.record_raw_event(&raw_event);
216 }
217}
218
219impl<'a> TimingGuard<'a> {
220 /// This method set a new `event_id` right before actually recording the
221 /// event.
222 #[inline]
223 pub fn finish_with_override_event_id(mut self, event_id: EventId) {
224 self.event_id = event_id;
225 // Let's be explicit about it: Dropping the guard will record the event.
226 drop(self)
227 }
228}
229
230// Make sure that `Profiler` can be used in a multithreaded context
231fn _assert_bounds() {
232 assert_bounds_inner(&Profiler::new(path_stem:""));
233 fn assert_bounds_inner<S: Sized + Send + Sync + 'static>(_: &S) {}
234}
235