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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
#![allow(unused)]

//! Here's an example of how to use some of FLAMEs APIs:
//!
//! ```
//! extern crate flame;
//!
//! use std::fs::File;
//!
//! pub fn main() {
//!     // Manual `start` and `end`
//!     flame::start("read file");
//!     let x = read_a_file();
//!     flame::end("read file");
//!
//!     // Time the execution of a closure.  (the result of the closure is returned)
//!     let y = flame::span_of("database query", || query_database());
//!
//!     // Time the execution of a block by creating a guard.
//!     let z = {
//!         let _guard = flame::start_guard("cpu-heavy calculation");
//!         cpu_heavy_operations_1();
//!         // Notes can be used to annotate a particular instant in time.
//!         flame::note("something interesting happened", None);
//!         cpu_heavy_operations_2()
//!     };
//!
//!     // Dump the report to disk
//!     flame::dump_html(&mut File::create("flame-graph.html").unwrap()).unwrap();
//!
//!     // Or read and process the data yourself!
//!     let spans = flame::spans();
//!
//!     println!("{} {} {}", x, y, z);
//! }
//!
//! # fn read_a_file() -> bool { true }
//! # fn query_database() -> bool { true }
//! # fn cpu_heavy_operations_1() {}
//! # fn cpu_heavy_operations_2() -> bool { true }
//! ```


#[macro_use]
extern crate lazy_static;
extern crate thread_id;
#[macro_use]
extern crate serde_derive;
#[cfg(feature = "json")]
extern crate serde;
#[cfg(feature = "json")]
extern crate serde_json;

mod html;

use std::cell::{RefCell, Cell};
use std::iter::Peekable;
use std::borrow::Cow;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use std::io::{Write, Error as IoError};

pub type StrCow = Cow<'static, str>;

lazy_static!(static ref ALL_THREADS: Mutex<Vec<(usize, Option<String>, PrivateFrame)>> = Mutex::new(Vec::new()););
thread_local!(static LIBRARY: RefCell<Library> = RefCell::new(Library::new()));

#[derive(Debug)]
struct Library {
    name: Option<String>,
    current: PrivateFrame,
    epoch: Instant,
}

#[derive(Debug)]
struct PrivateFrame {
    next_id: u32,
    all: Vec<Event>,
    id_stack: Vec<u32>,
}

#[derive(Debug)]
struct Event {
    id: u32,
    parent: Option<u32>,
    name: StrCow,
    collapse: bool,
    start_ns: u64,
    end_ns: Option<u64>,
    delta: Option<u64>,
    notes: Vec<Note>,
}

/// A named timespan.
///
/// The span is the most important feature of Flame.  It denotes
/// a chunk of time that is important to you.
///
/// The Span records
/// * Start and stop time
/// * A list of children (also called sub-spans)
/// * A list of notes
#[derive(Debug, Clone)]
#[cfg_attr(feature = "json", derive(Serialize))]
pub struct Span {
    /// The name of the span
    pub name: StrCow,
    /// The timestamp of the start of the span
    pub start_ns: u64,
    /// The timestamp of the end of the span
    pub end_ns: u64,
    /// The time that ellapsed between start_ns and end_ns
    pub delta: u64,
    /// How deep this span is in the tree
    pub depth: u16,
    /// A list of spans that occurred inside this one
    pub children: Vec<Span>,
    /// A list of notes that occurred inside this span
    pub notes: Vec<Note>,
    #[cfg_attr(feature = "json", serde(skip_serializing))]
    collapsable: bool,
    #[cfg_attr(feature = "json", serde(skip_serializing))]
    _priv: (),
}

/// A note for use in debugging.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "json", derive(Serialize))]
pub struct Note {
    /// A short name describing what happened at some instant in time
    pub name: StrCow,
    /// A longer description
    pub description: Option<StrCow>,
    /// The time that the note was added
    pub instant: u64,
    #[cfg_attr(feature = "json", serde(skip_serializing))]
    _priv: (),
}

/// A collection of events that happened on a single thread.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "json", derive(Serialize))]
pub struct Thread {
    pub id: usize,
    pub name: Option<String>,
    pub spans: Vec<Span>,
    #[cfg_attr(feature = "json", serde(skip_serializing))]
    _priv: (),
}

pub struct SpanGuard {
    name: Option<StrCow>,
    collapse: bool,
}

impl Drop for SpanGuard {
    fn drop(&mut self) {
        if ::std::thread::panicking() { return; }
        let name = self.name.take().unwrap();
        end_impl(name, self.collapse);
    }
}

impl SpanGuard {
    pub fn end(self) { }
    pub fn end_collapse(mut self) {
        self.collapse = true;
    }
}

fn ns_since_epoch(epoch: Instant) -> u64 {
    let elapsed = epoch.elapsed();
    elapsed.as_secs() * 1000_000_000 + elapsed.subsec_nanos() as u64
}

fn convert_events_to_span<'a, I>(events: I) -> Vec<Span>
where I: Iterator<Item = &'a Event> {
    let mut iterator = events.peekable();
    let mut v = vec![];
    while let Some(event) = iterator.next() {
        if let Some(span) = event_to_span(event, &mut iterator, 0) {
            v.push(span);
        }
    }
    v
}

fn event_to_span<'a, I: Iterator<Item = &'a Event>>(event: &Event, events: &mut Peekable<I>, depth: u16) -> Option<Span> {
    if event.end_ns.is_some() && event.delta.is_some() {
        let mut span = Span {
            name: event.name.clone(),
            start_ns: event.start_ns,
            end_ns: event.end_ns.unwrap(),
            delta: event.delta.unwrap(),
            depth: depth,
            children: vec![],
            notes: event.notes.clone(),
            collapsable: event.collapse,
            _priv: ()
        };

        loop {
            {
                match events.peek() {
                    Some(next) if next.parent != Some(event.id) => break,
                    None => break,
                    _ => {}
                }
            }

            let next = events.next().unwrap();
            let child = event_to_span(next, events, depth + 1);
            if let Some(child) = child {
                // Try to collapse with the previous span
                if span.children.len() != 0 && child.collapsable && child.children.len() == 0 {
                    let last = span.children.last_mut().unwrap();
                    if last.name == child.name && last.depth == child.depth {
                        last.end_ns = child.end_ns;
                        last.delta += child.delta;
                        continue;
                    }
                }

                // Otherwise, it's a new node
                span.children.push(child);
            }
        }
        Some(span)
    } else {
        None
    }
}

impl Span {
    #[cfg(feature = "json")]
    pub fn into_json(&self) -> String {
        ::serde_json::to_string_pretty(self).unwrap()
    }
}

impl Thread {
    #[cfg(feature = "json")]
    pub fn into_json(&self) -> String {
        ::serde_json::to_string_pretty(self).unwrap()
    }

    #[cfg(feature = "json")]
    pub fn into_json_list(threads: &Vec<Thread>) -> String {
        ::serde_json::to_string_pretty(threads).unwrap()
    }
}

impl Library {
    fn new() -> Library {
        Library {
            name: ::std::thread::current().name().map(Into::into),
            current: PrivateFrame {
                all: vec![],
                id_stack: vec![],
                next_id: 0,
            },
            epoch: Instant::now(),
        }
    }
}

fn commit_impl(library: &mut Library) {
    use std::thread;
    use std::sync::MutexGuard;
    use std::mem;
    
    let mut frame = PrivateFrame {
        all: vec![],
        id_stack: vec![],
        next_id: 0,
    };

    mem::swap(&mut frame, &mut library.current);

    let mut handle = if let Ok(handle) = ALL_THREADS.lock() {
        handle
    } else {
        return;
    };

    let thread_name = library.name.clone();

    let thread_id = ::thread_id::get();
    handle.push((thread_id, thread_name, frame))
}

pub fn commit_thread() {
    LIBRARY.with(|library| commit_impl(&mut *library.borrow_mut()));
}

impl Drop for Library {
    fn drop(&mut self) {
        if ::std::thread::panicking() { return; }
        commit_impl(self);
    }
}

/// Starts a `Span` and also returns a `SpanGuard`.
///
/// When the `SpanGuard` is dropped (or `.end()` is called on it),
/// the span will automatically be ended.
pub fn start_guard<S: Into<StrCow>>(name: S) -> SpanGuard {
    let name = name.into();
    start(name.clone());
    SpanGuard { name: Some(name), collapse: false }
}

/// Starts and ends a `Span` that lasts for the duration of the
/// function `f`.
pub fn span_of<S, F, R>(name: S, f: F) -> R where
S: Into<StrCow>,
F: FnOnce() -> R
{
    let name = name.into();
    start(name.clone());
    let r = f();
    end(name);
    r
}

/// Starts a new Span
pub fn start<S: Into<StrCow>>(name: S) {
    LIBRARY.with(|library| {
        let mut library = library.borrow_mut();
        let epoch = library.epoch;

        let collector = &mut library.current;
        let id = collector.next_id;
        collector.next_id += 1;

        let this = Event {
            id: id,
            parent: collector.id_stack.last().cloned(),
            name: name.into(),
            collapse: false,
            start_ns: ns_since_epoch(epoch),
            end_ns: None,
            delta: None,
            notes: vec![]
        };

        collector.all.push(this);
        collector.id_stack.push(id);
    });
}

fn end_impl<S: Into<StrCow>>(name: S, collapse: bool) -> u64 {
    use std::thread;

    let name = name.into();
    let delta = LIBRARY.with(|library| {
        let mut library = library.borrow_mut();
        let epoch = library.epoch;
        let collector = &mut library.current;

        let current_id = match collector.id_stack.pop() {
            Some(id) => id,
            None if thread::panicking() => 0,
            None => panic!("flame::end({:?}) called without a currently running span!", &name)
        };

        let event = &mut collector.all[current_id as usize];

        if event.name != name {
            panic!("flame::end({}) attempted to end {}", &name, event.name);
        }

        let timestamp = ns_since_epoch(epoch);
        event.end_ns = Some(timestamp);
        event.collapse = collapse;
        event.delta = Some(timestamp - event.start_ns);
        event.delta
    });

    match delta {
        Some(d) => d,
        None => 0, // panicking
    }
}

/// Ends the current Span and returns the number
/// of nanoseconds that passed.
pub fn end<S: Into<StrCow>>(name: S) -> u64 {
    end_impl(name, false)
}

/// Ends the current Span and returns a given result.
///
/// This is mainly useful for code generation / plugins where
/// wrapping all returned expressions is easier than creating
/// a temporary variable to hold the result.
pub fn end_with<S: Into<StrCow>, R>(name: S, result: R) -> R {
    end_impl(name, false);
    result
}

/// Ends the current Span and returns the number of
/// nanoseconds that passed.
///
/// If this span is a leaf node, and the previous span
/// has the same name and depth, then collapse this
/// span into the previous one.  The end_ns field will
/// be updated to the end time of *this* span, and the
/// delta field will be the sum of the deltas from this
/// and the previous span.
///
/// This means that it is possible for end_ns - start_n
/// to not be equal to delta.
pub fn end_collapse<S: Into<StrCow>>(name: S) -> u64 {
    end_impl(name, false)
}

/// Records a note on the current Span.
pub fn note<S: Into<StrCow>>(name: S, description: Option<S>) {
    let name = name.into();
    let description = description.map(Into::into);

    LIBRARY.with(|library| {
        let mut library = library.borrow_mut();
        let epoch = library.epoch;

        let collector = &mut library.current;

        let current_id = match collector.id_stack.last() {
            Some(id) => *id,
            None => panic!("flame::note({}, {:?}) called without a currently running span!",
                           &name, &description)
        };

        let event = &mut collector.all[current_id as usize];
        event.notes.push(Note {
            name: name,
            description: description,
            instant: ns_since_epoch(epoch),
            _priv: ()
        });
    });
}

/// Clears all of the recorded info that Flame has
/// tracked.
pub fn clear() {
    LIBRARY.with(|library| {
        let mut library = library.borrow_mut();
        library.current = PrivateFrame {
            all: vec![],
            id_stack: vec![],
            next_id: 0,
        };
        library.epoch = Instant::now();
    });

    let mut handle = ALL_THREADS.lock().unwrap();
    handle.clear();
}

/// Returns a list of spans from the current thread
pub fn spans() -> Vec<Span> {
    LIBRARY.with(|library| {
        let library = library.borrow();
        let cur = &library.current;
        convert_events_to_span(cur.all.iter())
    })
}

pub fn threads() -> Vec<Thread> {
    let mut handle = ALL_THREADS.lock().unwrap();

    let my_thread_name = ::std::thread::current().name().map(Into::into);
    let my_thread_id = ::thread_id::get();

    let mut out = vec![ Thread {
        id: my_thread_id,
        name: my_thread_name,
        spans: spans(),
        _priv: (),
    }];

    for &(id, ref name, ref frm) in &*handle {
        out.push(Thread {
            id: id,
            name: name.clone(),
            spans: convert_events_to_span(frm.all.iter()),
            _priv: (),
        });
    }

    out
}

/// Prints all of the frames to stdout.
pub fn debug() {
    LIBRARY.with(|library| {
        println!("{:?}", library);
    });
}

pub fn dump_text_to_writer<W: Write>(mut out: W) -> Result<(), IoError>  {
    fn print_span<W: Write>(span: &Span, out: &mut W) -> Result<f32, IoError> {
        let mut buf = String::new();
        for _ in 0 .. span.depth {
            buf.push_str("  ");
        }
        buf.push_str("| ");
        let ms = span.delta as f32 / 1000000.0;
        buf.push_str(&format!("{}: {}ms", span.name, ms));
        writeln!(out, "{}", buf)?;
        let mut missing = ms;
        for child in &span.children {
            missing -= print_span(child, out)?;
        }

        if !span.children.is_empty() {
            let mut buf = String::new();
            for _ in 0 .. (span.depth + 1) {
                buf.push_str("  ");
            }
            buf.push_str("+ ");
            buf.push_str(&format!("{}ms", missing));
            writeln!(out, "{}", buf)?;
        }

        Ok(ms)
    }

    for thread in threads() {
        writeln!(out, "THREAD: {}", thread.id)?;
        for span in thread.spans {
            print_span(&span, &mut out)?;
        }
        writeln!(out, "")?;
    }
    Ok(())
}

pub fn dump_stdout() {
    let stdout = ::std::io::stdout();
    let stdout = stdout.lock();
    dump_text_to_writer(stdout);
}

#[cfg(feature="json")]
pub fn dump_json<W: std::io::Write>(out: &mut W) -> std::io::Result<()> {
    out.write_all(serde_json::to_string_pretty(&threads()).unwrap().as_bytes())
}

pub use html::dump_html;