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
use std::{sync::Mutex, time::Instant};

use rustc_hash::FxHashMap;
use tabled::{settings::Style, Table, Tabled};

lazy_static! {
    pub static ref PROFILER: Mutex<FxHashMap<&'static str, (u128, usize)>> = Mutex::default();
}

pub struct ProfSpan {
    name: &'static str,
    start: Instant
}

impl ProfSpan {
    pub fn new(name: &'static str) -> Self {
        ProfSpan { start: Instant::now(), name }
    }

    pub fn end(&self) {
        let elapsed = self.start.elapsed().as_nanos();

        let mut p_entry = PROFILER.lock().unwrap();
        let entry_data = p_entry.entry(self.name).or_insert((0, 0));

        entry_data.0 += elapsed;
        entry_data.1 += 1;
    }
}

#[macro_export]
macro_rules! profile {
    ($name: expr, $expr: expr) => {
        {
            let span = $crate::profiling::ProfSpan::new($name);

            let res = $expr;
    
            span.end();
    
            res    
        }
    };
}

#[derive(Tabled)]
struct ProfilerEntry {
    name: &'static str,
    total_time: u128,
    time: u128,
    count: usize,
    percentage: f32
}

pub fn clear_profiler() {
    PROFILER.lock().unwrap().clear();
}

pub fn print_profiler_results() {
    let mut entries = PROFILER.lock().unwrap().iter().map(|(a, b)| (*a, *b)).collect::<Vec<_>>();
    entries.sort_by_key(|(_, i)| *i);
    entries.reverse();

    let total_time = entries.iter().map(|(_, (i, _))| *i).sum::<u128>();

    let table = Table::new(
        entries.into_iter().map(|(name, (time, count))| ProfilerEntry {
            name,
            total_time: time / 1000000,
            count,
            time: time / count as u128,
            percentage: (time as f64 / total_time as f64) as f32,
        })
    ).with(Style::modern_rounded()).to_string();

    print!("{}", table);
}