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
use std::io::Result;
use std::process::{Command, ExitStatus};
use std::time::{Duration, Instant};
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Timings {
pub wall_time: Duration,
pub user_time: f64,
pub sys_time: f64,
}
pub fn time_cmd(cmd: Command) -> Result<(Timings, ExitStatus)> {
#[cfg(unix)]
let ret = time_cmd_posix(cmd)?;
#[cfg(not(unix))]
let ret = time_cmd_fallback(cmd)?;
Ok(ret)
}
#[cfg(not(unix))]
fn time_cmd_fallback(mut cmd: Command) -> Result<(Timings, ExitStatus)> {
let ts = Instant::now();
let status = cmd.spawn()?.wait()?;
let d = ts.elapsed();
Ok((
Timings {
wall_time: d,
user_time: std::f64::NAN,
sys_time: std::f64::NAN,
},
status,
))
}
#[cfg(unix)]
fn time_cmd_posix(mut cmd: Command) -> Result<(Timings, ExitStatus)> {
let mut tms_before = libc::tms {
tms_utime: 0,
tms_stime: 0,
tms_cutime: 0,
tms_cstime: 0,
};
let mut tms_after = tms_before;
unsafe { libc::times(&mut tms_before as *mut libc::tms) };
let ts = Instant::now();
let status = cmd.spawn()?.wait()?;
let d = ts.elapsed();
unsafe { libc::times(&mut tms_after as *mut libc::tms) };
let ticks_per_sec = unsafe { libc::sysconf(libc::_SC_CLK_TCK) } as f64;
let utime = (tms_after.tms_cutime - tms_before.tms_cutime) as f64 / ticks_per_sec;
let stime = (tms_after.tms_cstime - tms_before.tms_cstime) as f64 / ticks_per_sec;
Ok((
Timings {
wall_time: d,
user_time: utime,
sys_time: stime,
},
status,
))
}