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
mod checkpoint;

use checkpoint::Checkpoint;
use lazy_static::lazy_static;
use std::fs::OpenOptions;
use std::sync::Mutex;
use std::io::Write;

#[derive(Clone)]
enum To {
    Stderr,
    File(String),
}

// The main point of this crate is to make it easy to measure the duration between
// two arbitrary code locations. Globals are generally evil, but in this case it is
// exactly what we want, since passing a struct around from the first place
// to the second place often would be prohibitively much work.
lazy_static! {
    static ref LAST_CHECKPOINT: Mutex<Option<Checkpoint>> = Mutex::from(None);
    static ref TO: Mutex<To> = Mutex::from(To::Stderr);
}

pub fn to_file(path: &str) {
    let mut to = TO.lock().unwrap();
    *to = To::File(String::from(path));
}

pub fn checkpoint(name: &str) {
    let output = update_checkpoint(name);
    if let Some(output) = output {
        print(&output);
    }
}

fn update_checkpoint(new_name: &str) -> Option<String> {
    let mut last_checkpoint = LAST_CHECKPOINT.lock().unwrap();

    let output = match &*last_checkpoint {
        // No ouput first checkpoint to minimize effects on duration measurements
        None => None,
        Some(checkpoint) => Some(format!(
            "{:?} from '{}' to '{}'\n",
            checkpoint.instant.elapsed(),
            checkpoint.name,
            new_name,
        )),
    };

    *last_checkpoint = Some(Checkpoint::new(new_name));

    output
}

fn print(output: &str) {
    let to;
    {
        // Hold lock for minimal amount of time for minimal risk of e.g. lock poisoning
        to = TO.lock().unwrap().clone();
    }

    match to {
        To::Stderr => {
            eprint!("{}", output);
        }
        To::File(path) => {
            let mut file = OpenOptions::new().create(true).append(true).open(&path).unwrap();
            if let Err(e) = write!(file, "{}", output) {
                eprint!("Error while writing to {}: {:?}", &path, e)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::thread::sleep;
    use std::time::Duration;

    // TODO: Port this test to and write more tests using assert_cmd
    #[test]
    fn basic_to_file() {
        // Do the test
        to_file("/tmp/com.setofskills.global_duration.test-output.txt");
        checkpoint("checkpoint 1");
        sleep(Duration::from_millis(1000));
        checkpoint("checkpoint 2");
        sleep(Duration::from_millis(2000));
        checkpoint("checkpoint 3");

        // TODO: Assert result
        // let actual_contents = std::fs::read_to_string("/tmp/global-duration-to-file.test-output.txt").unwrap();
    }
}