1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
|
//! Performance timing for Typst.
use std::io::Write;
use std::num::NonZeroU64;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use parking_lot::Mutex;
use serde::ser::SerializeSeq;
use serde::{Serialize, Serializer};
/// Creates a timing scope around an expression.
///
/// The output of the expression is returned.
///
/// The scope will be named `name` and will have the span `span`. The span is
/// optional.
///
/// ## Example
///
/// ```rs
/// // With a scope name and span.
/// timed!(
/// "my scope",
/// span = Span::detached(),
/// std::thread::sleep(std::time::Duration::from_secs(1)),
/// );
///
/// // With a scope name and no span.
/// timed!(
/// "my scope",
/// std::thread::sleep(std::time::Duration::from_secs(1)),
/// );
/// ```
#[macro_export]
macro_rules! timed {
($name:expr, span = $span:expr, $body:expr $(,)?) => {{
let __scope = $crate::TimingScope::with_span($name, Some($span));
$body
}};
($name:expr, $body:expr $(,)?) => {{
let __scope = $crate::TimingScope::new($name);
$body
}};
}
thread_local! {
/// Data that is initialized once per thread.
static THREAD_DATA: ThreadData = ThreadData {
id: {
// We only need atomicity and no synchronization of other
// operations, so `Relaxed` is fine.
static COUNTER: AtomicU64 = AtomicU64::new(1);
COUNTER.fetch_add(1, Ordering::Relaxed)
},
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
timer: WasmTimer::new(),
};
}
/// Whether the timer is enabled. Defaults to `false`.
static ENABLED: AtomicBool = AtomicBool::new(false);
/// The list of collected events.
static EVENTS: Mutex<Vec<Event>> = Mutex::new(Vec::new());
/// Enable the timer.
#[inline]
pub fn enable() {
// We only need atomicity and no synchronization of other
// operations, so `Relaxed` is fine.
ENABLED.store(true, Ordering::Relaxed);
}
/// Whether the timer is enabled.
#[inline]
pub fn is_enabled() -> bool {
ENABLED.load(Ordering::Relaxed)
}
/// Clears the recorded events.
#[inline]
pub fn clear() {
EVENTS.lock().clear();
}
/// Export data as JSON for Chrome's tracing tool.
///
/// The `source` function is called for each span to get the source code
/// location of the span. The first element of the tuple is the file path and
/// the second element is the line number.
pub fn export_json<W: Write>(
writer: W,
mut source: impl FnMut(NonZeroU64) -> (String, u32),
) -> Result<(), String> {
#[derive(Serialize)]
struct Entry {
name: &'static str,
cat: &'static str,
ph: &'static str,
ts: f64,
pid: u64,
tid: u64,
args: Option<Args>,
}
#[derive(Serialize)]
struct Args {
file: String,
line: u32,
}
let lock = EVENTS.lock();
let events = lock.as_slice();
let mut serializer = serde_json::Serializer::new(writer);
let mut seq = serializer
.serialize_seq(Some(events.len()))
.map_err(|e| format!("failed to serialize events: {e}"))?;
for event in events.iter() {
seq.serialize_element(&Entry {
name: event.name,
cat: "typst",
ph: match event.kind {
EventKind::Start => "B",
EventKind::End => "E",
},
ts: event.timestamp.micros_since(events[0].timestamp),
pid: 1,
tid: event.thread_id,
args: event.span.map(&mut source).map(|(file, line)| Args { file, line }),
})
.map_err(|e| format!("failed to serialize event: {e}"))?;
}
seq.end().map_err(|e| format!("failed to serialize events: {e}"))?;
Ok(())
}
/// A scope that records an event when it is dropped.
pub struct TimingScope {
name: &'static str,
span: Option<NonZeroU64>,
thread_id: u64,
}
impl TimingScope {
/// Create a new scope if timing is enabled.
#[inline]
pub fn new(name: &'static str) -> Option<Self> {
Self::with_span(name, None)
}
/// Create a new scope with a span if timing is enabled.
///
/// The span is a raw number because `typst-timing` can't depend on
/// `typst-syntax` (or else `typst-syntax` couldn't depend on
/// `typst-timing`).
#[inline]
pub fn with_span(name: &'static str, span: Option<NonZeroU64>) -> Option<Self> {
if is_enabled() {
return Some(Self::new_impl(name, span));
}
None
}
/// Create a new scope without checking if timing is enabled.
fn new_impl(name: &'static str, span: Option<NonZeroU64>) -> Self {
let (thread_id, timestamp) =
THREAD_DATA.with(|data| (data.id, Timestamp::now_with(data)));
EVENTS.lock().push(Event {
kind: EventKind::Start,
timestamp,
name,
span,
thread_id,
});
Self { name, span, thread_id }
}
}
impl Drop for TimingScope {
fn drop(&mut self) {
let timestamp = Timestamp::now();
EVENTS.lock().push(Event {
kind: EventKind::End,
timestamp,
name: self.name,
span: self.span,
thread_id: self.thread_id,
});
}
}
/// An event that has been recorded.
struct Event {
/// Whether this is a start or end event.
kind: EventKind,
/// The time at which this event occurred.
timestamp: Timestamp,
/// The name of this event.
name: &'static str,
/// The raw value of the span of code that this event was recorded in.
span: Option<NonZeroU64>,
/// The thread ID of this event.
thread_id: u64,
}
/// Whether an event marks the start or end of a scope.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum EventKind {
Start,
End,
}
/// A cross-platform way to get the current time.
#[derive(Copy, Clone)]
struct Timestamp {
#[cfg(not(target_arch = "wasm32"))]
inner: std::time::SystemTime,
#[cfg(target_arch = "wasm32")]
inner: f64,
}
impl Timestamp {
fn now() -> Self {
#[cfg(target_arch = "wasm32")]
return THREAD_DATA.with(Self::now_with);
#[cfg(not(target_arch = "wasm32"))]
Self { inner: std::time::SystemTime::now() }
}
#[allow(unused_variables)]
fn now_with(data: &ThreadData) -> Self {
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
return Self { inner: data.timer.now() };
#[cfg(all(target_arch = "wasm32", not(feature = "wasm")))]
return Self { inner: 0.0 };
#[cfg(not(target_arch = "wasm32"))]
Self::now()
}
fn micros_since(self, start: Self) -> f64 {
#[cfg(target_arch = "wasm32")]
return (self.inner - start.inner) * 1000.0;
#[cfg(not(target_arch = "wasm32"))]
(self
.inner
.duration_since(start.inner)
.unwrap_or(std::time::Duration::ZERO)
.as_nanos() as f64
/ 1_000.0)
}
}
/// Per-thread data.
struct ThreadData {
/// The thread's ID.
///
/// In contrast to `std::thread::current().id()`, this is wasm-compatible
/// and also a bit cheaper to access because the std version does a bit more
/// stuff (including cloning an `Arc`).
id: u64,
/// A way to get the time from WebAssembly.
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
timer: WasmTimer,
}
/// A way to get the time from WebAssembly.
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
struct WasmTimer {
/// The cached JS performance handle for the thread.
perf: web_sys::Performance,
/// The cached JS time origin.
time_origin: f64,
}
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
impl WasmTimer {
fn new() -> Self {
// Retrieve `performance` from global object, either the window or
// globalThis.
let perf = web_sys::window()
.and_then(|window| window.performance())
.or_else(|| {
use web_sys::wasm_bindgen::JsCast;
web_sys::js_sys::global()
.dyn_into::<web_sys::WorkerGlobalScope>()
.ok()
.and_then(|scope| scope.performance())
})
.expect("failed to get JS performance handle");
// Every thread gets its own time origin. To make the results consistent
// across threads, we need to add this to each `now()` call.
let time_origin = perf.time_origin();
Self { perf, time_origin }
}
fn now(&self) -> f64 {
self.time_origin + self.perf.now()
}
}
|