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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#![warn(missing_docs)]
#![cfg_attr(not(test), no_std)]
use core::sync::atomic::{AtomicU8, Ordering};
#[cfg(test)]
mod mock;
#[cfg(feature = "proc-macros")]
pub use embedded_profiling_proc_macros::profile_function;
pub use fugit;
#[cfg(not(feature = "container-u64"))]
type PrivContainer = u32;
#[cfg(feature = "container-u64")]
type PrivContainer = u64;
pub type EPContainer = PrivContainer;
pub type EPDuration = fugit::MicrosDuration<EPContainer>;
pub type EPInstant = fugit::Instant<EPContainer, 1, 1_000_000>;
pub struct EPSnapshot {
pub name: &'static str,
pub duration: EPDuration,
}
impl core::fmt::Display for EPSnapshot {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "<EPSS {}: {}>", self.name, self.duration)
}
}
pub trait EmbeddedProfiler {
fn read_clock(&self) -> EPInstant;
fn log_snapshot(&self, _snapshot: &EPSnapshot) {}
fn at_start(&self) {}
fn at_end(&self) {}
fn start_snapshot(&self) -> EPInstant {
self.at_start();
self.read_clock()
}
fn end_snapshot(&self, start: EPInstant, name: &'static str) -> Option<EPSnapshot> {
self.at_end();
let now = self.read_clock();
now.checked_duration_since(start)
.map(|duration| EPSnapshot { name, duration })
}
}
struct NoopProfiler;
impl EmbeddedProfiler for NoopProfiler {
fn read_clock(&self) -> EPInstant {
EPInstant::from_ticks(0)
}
fn log_snapshot(&self, _snapshot: &EPSnapshot) {}
}
static mut PROFILER: &dyn EmbeddedProfiler = &NoopProfiler;
const UNINITIALIZED: u8 = 0;
const INITIALIZED: u8 = 2;
static STATE: AtomicU8 = AtomicU8::new(UNINITIALIZED);
#[derive(Debug)]
pub struct SetProfilerError;
pub unsafe fn set_profiler(
profiler: &'static dyn EmbeddedProfiler,
) -> Result<(), SetProfilerError> {
match STATE.load(Ordering::Acquire) {
UNINITIALIZED => {
PROFILER = profiler;
STATE.store(INITIALIZED, Ordering::Release);
Ok(())
}
INITIALIZED => Err(SetProfilerError),
_ => unreachable!(),
}
}
#[inline]
pub fn profiler() -> &'static dyn EmbeddedProfiler {
if STATE.load(Ordering::Acquire) == INITIALIZED {
unsafe { PROFILER }
} else {
static NOP: NoopProfiler = NoopProfiler;
&NOP
}
}
#[inline]
pub fn start_snapshot() -> EPInstant {
profiler().start_snapshot()
}
#[inline]
pub fn end_snapshot(start: EPInstant, name: &'static str) -> Option<EPSnapshot> {
profiler().end_snapshot(start, name)
}
#[inline]
pub fn log_snapshot(snapshot: &EPSnapshot) {
profiler().log_snapshot(snapshot);
}
pub fn profile<T, R>(name: &'static str, target: T) -> R
where
T: Fn() -> R,
{
let start = start_snapshot();
let ret = target();
if let Some(snapshot) = end_snapshot(start, name) {
log_snapshot(&snapshot);
}
ret
}
#[cfg(test)]
mod test {
use super::mock::StdMockProfiler;
use super::*;
#[cfg(feature = "proc-macros")]
use crate as embedded_profiling;
use std::sync::Once;
static INIT_PROFILER: Once = Once::new();
static mut MOCK_PROFILER: Option<StdMockProfiler> = None;
fn set_profiler() {
INIT_PROFILER.call_once(|| unsafe {
if MOCK_PROFILER.is_none() {
MOCK_PROFILER = Some(StdMockProfiler::default());
}
super::set_profiler(MOCK_PROFILER.as_ref().unwrap()).unwrap();
});
}
#[test]
#[serial_test::serial]
fn basic_duration() {
let profiler = StdMockProfiler::default();
let start = profiler.start_snapshot();
std::thread::sleep(std::time::Duration::from_millis(25));
let end = profiler.end_snapshot(start, "basic_dur").unwrap();
profiler.log_snapshot(&end);
}
#[test]
#[serial_test::serial]
fn basic_duration_and_set_profiler() {
set_profiler();
let start = start_snapshot();
std::thread::sleep(std::time::Duration::from_millis(25));
let end = end_snapshot(start, "basic_dur").unwrap();
log_snapshot(&end);
}
#[test]
#[serial_test::serial]
fn profile_closure() {
set_profiler();
profile("25ms closure", || {
std::thread::sleep(std::time::Duration::from_millis(25));
});
}
#[cfg(feature = "proc-macros")]
#[test]
#[serial_test::serial]
fn profile_proc_macro() {
#[profile_function]
fn delay_25ms() {
std::thread::sleep(std::time::Duration::from_millis(25));
}
set_profiler();
delay_25ms();
}
#[cfg(feature = "proc-macros")]
#[test]
#[serial_test::serial]
fn check_call_and_order() {
use Ordering::SeqCst;
#[profile_function]
fn delay_25ms() {
std::thread::sleep(std::time::Duration::from_millis(25));
}
set_profiler();
delay_25ms();
let stats = unsafe { &MOCK_PROFILER.as_ref().unwrap().funcs_called };
let at_start_was_called = stats.at_start.called.load(SeqCst);
let read_clock_was_called = stats.read_clock.called.load(SeqCst);
let at_end_was_called = stats.at_end.called.load(SeqCst);
let log_snapshot_was_called = stats.log_snapshot.called.load(SeqCst);
let at_start_at = stats.at_start.at.load(SeqCst);
let read_clock_at = stats.read_clock.at.load(SeqCst);
let at_end_at = stats.at_end.at.load(SeqCst);
let log_snapshot_at = stats.log_snapshot.at.load(SeqCst);
if at_start_was_called {
println!("at_start called #{}", at_start_at);
} else {
println!("at_start not called");
}
if read_clock_was_called {
println!("read_clock called #{}", read_clock_at);
} else {
println!("read_clock not called");
}
if at_end_was_called {
println!("at_end called #{}", at_end_at);
} else {
println!("at_end not called");
}
if log_snapshot_was_called {
println!("log_snapshot called #{}", log_snapshot_at);
} else {
println!("log_snapshot not called");
}
assert!(at_start_was_called, "'at_start' was never called");
assert!(read_clock_was_called, "'read_clock' was never called");
assert!(at_end_was_called, "'at_end' was never called");
assert!(log_snapshot_was_called, "'log_snapshot' was never called");
assert_eq!(at_start_at, 0, "'at_start' called at wrong time");
assert_eq!(read_clock_at, 1, "'read_clock' called at wrong time");
assert_eq!(at_end_at, 2, "'at_end' called at wrong time");
assert_eq!(log_snapshot_at, 3, "'log_snapshot' called at wrong time");
}
}