gloo_console_timer/
lib.rs

1/*!
2
3The `console.time` and `console.timeEnd` functions allow you to log the
4timing of named operations to the browser's developer tools console. You
5call `console.time("foo")` when the operation begins, and call
6`console.timeEnd("foo")` when it finishes.
7
8Additionally, these measurements will show up in your browser's profiler's
9"timeline" or "waterfall" view.
10
11[See MDN for more info](https://developer.mozilla.org/en-US/docs/Web/API/console#Timers).
12
13This API wraps both the `time` and `timeEnd` calls into a single type
14named `ConsoleTimer`, ensuring both are called.
15
16## Scoped Measurement
17
18Wrap code to be measured in a closure with `ConsoleTimer::scope`.
19
20```no_run
21use gloo_console_timer::ConsoleTimer;
22
23let value = ConsoleTimer::scope("foo", || {
24    // Place code to be measured here
25    // Optionally return a value.
26});
27```
28
29## RAII-Style Measurement
30
31For scenarios where `ConsoleTimer::scope` can't be used, like with
32asynchronous operations, you can use `ConsoleTimer::new` to create a timer.
33The measurement ends when the timer object goes out of scope / is dropped.
34
35```no_run
36use gloo_console_timer::ConsoleTimer;
37use gloo_timers::callback::Timeout;
38
39// Start timing a new operation.
40let timer = ConsoleTimer::new("foo");
41
42// And then asynchronously finish timing.
43let timeout = Timeout::new(1_000, move || {
44    drop(timer);
45});
46```
47 */
48
49#![deny(missing_docs, missing_debug_implementations)]
50
51use web_sys::console;
52
53/// A console time measurement.
54///
55/// See `ConsoleTimer::scope` for starting a labeled time measurement
56/// of code wrapped in a closure.
57#[derive(Debug)]
58pub struct ConsoleTimer<'a> {
59    label: &'a str,
60}
61
62impl<'a> ConsoleTimer<'a> {
63    /// Starts a console time measurement. The measurement
64    /// ends when the constructed `ConsoleTimer` object is dropped.
65    ///
66    /// # Example
67    ///
68    /// ```no_run
69    /// use gloo_console_timer::ConsoleTimer;
70    ///
71    /// let _timer = ConsoleTimer::new("foo");
72    /// ```
73    pub fn new(label: &'a str) -> ConsoleTimer<'a> {
74        console::time_with_label(label);
75        ConsoleTimer { label }
76    }
77
78    /// Starts a scoped console time measurement
79    ///
80    /// # Example
81    ///
82    /// ```no_run
83    /// use gloo_console_timer::ConsoleTimer;
84    ///
85    /// let value = ConsoleTimer::scope("foo", || {
86    ///     // Code to measure here
87    /// });
88    /// ```
89    pub fn scope<F, T>(label: &str, f: F) -> T
90    where
91        F: FnOnce() -> T,
92    {
93        let _timer = ConsoleTimer::new(label);
94        f()
95    }
96}
97
98impl<'a> Drop for ConsoleTimer<'a> {
99    fn drop(&mut self) {
100        console::time_end_with_label(self.label);
101    }
102}