|
| 1 | +use std::collections::HashMap; |
| 2 | +use std::path::PathBuf; |
| 3 | +use std::time::Duration; |
| 4 | +use measureme::{ProfilingData, TimestampKind, Event}; |
| 5 | + |
| 6 | +use structopt::StructOpt; |
| 7 | + |
| 8 | +#[derive(StructOpt, Debug)] |
| 9 | +struct Opt { |
| 10 | + file_prefix: PathBuf, |
| 11 | +} |
| 12 | + |
| 13 | +fn main() { |
| 14 | + let opt = Opt::from_args(); |
| 15 | + |
| 16 | + let data = ProfilingData::new(&opt.file_prefix); |
| 17 | + |
| 18 | + let mut cumulative_time = HashMap::<_, Duration>::new(); |
| 19 | + let mut threads = HashMap::<_, Vec<Event>>::new(); |
| 20 | + |
| 21 | + for event in data.iter() { |
| 22 | + match event.timestamp_kind { |
| 23 | + TimestampKind::Start => { |
| 24 | + let thread_stack = threads.entry(event.thread_id).or_default(); |
| 25 | + |
| 26 | + if let Some(prev_event) = thread_stack.last() { |
| 27 | + //count the time run so far for this event |
| 28 | + let duration = |
| 29 | + event.timestamp.duration_since(prev_event.timestamp) |
| 30 | + .unwrap_or(Duration::from_nanos(0)); |
| 31 | + *cumulative_time.entry(prev_event.label.clone()).or_default() += duration; |
| 32 | + } |
| 33 | + |
| 34 | + thread_stack.push(event); |
| 35 | + }, |
| 36 | + TimestampKind::Instant => { }, |
| 37 | + TimestampKind::End => { |
| 38 | + let thread_stack = threads.get_mut(&event.thread_id).unwrap(); |
| 39 | + let start_event = thread_stack.pop().unwrap(); |
| 40 | + assert_eq!(start_event.event_kind, event.event_kind); |
| 41 | + assert_eq!(start_event.label, event.label); |
| 42 | + assert_eq!(start_event.timestamp_kind, TimestampKind::Start); |
| 43 | + |
| 44 | + //track the time for this event |
| 45 | + let duration = |
| 46 | + event.timestamp |
| 47 | + .duration_since(start_event.timestamp) |
| 48 | + .unwrap_or(Duration::from_nanos(0)); |
| 49 | + *cumulative_time.entry(start_event.label.clone()).or_default() += duration; |
| 50 | + |
| 51 | + //now adjust the previous event's start time so that it "started" right now |
| 52 | + if let Some(previous_event) = thread_stack.last_mut() { |
| 53 | + assert_eq!(TimestampKind::Start, previous_event.timestamp_kind); |
| 54 | + previous_event.timestamp = event.timestamp; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + let mut total_time = Duration::from_nanos(0); |
| 61 | + |
| 62 | + let mut times: Vec<_> = cumulative_time.iter().collect(); |
| 63 | + times.sort_by_key(|(_, v)| *v); |
| 64 | + times.reverse(); |
| 65 | + for (k, v) in times { |
| 66 | + total_time += *v; |
| 67 | + println!("{}- {:?}", k, v); |
| 68 | + } |
| 69 | + |
| 70 | + println!("Total cpu time: {:?}", total_time); |
| 71 | +} |
0 commit comments