Merge pull request #965 from sharkdp/codex/wait4-resource-usage
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Use `wait4` for per-command resource usage on Unix
authored by David Peter · committed by GitHub · parents 430dc5e, c72a4c7 · Browse files · 3 files·+73 added−97 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+73 added−97 removed
- other:+73 added−97 removed
Provenance
- Commit
e43bf85- Tree
cdc04c5- Author
David Peter <sharkdp@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
430dc5e- Parent 2
c72a4c7
3 files changed+73 added−97 removed
modified:src/quantity/mod.rs+3 added-1 removed
1 unmodified line2 3 pub use uom::num_traits::Zero;4 pub use uom::si::f64::{Information, Ratio, Time};5 pub use uom::si::information::byte;6+#[cfg(any(not(windows), test))]7+pub use uom::si::information::kibibyte;8 pub use uom::si::ratio::ratio;9 #[cfg(any(not(windows), test))]10 pub use uom::si::time::microsecond;11 pub use uom::si::time::{nanosecond, second};44 unmodified lines56 }57 }58 59 #[cfg(test)]58-use uom::si::{information::kibibyte, time::millisecond};60+use uom::si::time::millisecond;61 62 #[test]63 fn test_time() {64 let time = Time::new::<millisecond>(123.4);73 unmodified linesmodified:src/timer/mod.rs+6 added-13 removed
22 unmodified lines23 use std::process::{ChildStdout, Command};24 25 use anyhow::Result;26 27-#[cfg(not(windows))]28-#[derive(Debug, Copy, Clone)]29-struct CPUTimes {30- /// Total amount of time spent executing in user mode31- pub user_usec: i64,32-33- /// Total amount of time spent executing in kernel mode34- pub system_usec: i64,35-36- /// Maximum amount of memory used by the process, in bytes37- pub memory_usage_byte: u64,38-}39-27 /// Discard the output of a child process.28 fn discard(output: ChildStdout) {29 const CHUNK_SIZE: usize = 64 << 10;30 50 unmodified lines81 // Handle CommandOutputPolicy::Pipe82 discard(output);83 }84 85+ #[cfg(not(windows))]86+ let (time_user, time_system, peak_memory_usage, exit_status) = cpu_timer.stop(child)?;87+88+ #[cfg(windows)]89 let exit_status = child.wait()?;90 91 let time_wall_clock = wallclock_timer.stop();92+93+ #[cfg(windows)]94 let (time_user, time_system, peak_memory_usage) = cpu_timer.stop();95 96 Ok(Measurement {97 time_wall_clock,6 unmodified linesmodified:src/timer/unix_timer.rs+64 added-83 removed
1 #![cfg(not(windows))]2 3-use std::convert::TryFrom;4-use std::mem;3+use std::io;4+use std::mem::MaybeUninit;5+use std::os::unix::process::ExitStatusExt;6+use std::process::{Child, ExitStatus};7 6-use crate::quantity::{byte, microsecond, Information, Time};7-use crate::timer::CPUTimes;8+use anyhow::Result;9 10+use crate::quantity::{byte, kibibyte, microsecond, second, Information, Time};11+12 #[derive(Debug, Copy, Clone)]10-pub struct CPUInterval {13+struct ResourceUsage {14 /// Total amount of time spent executing in user mode12- pub user: Time,15+ pub time_user: Time,16 17 /// Total amount of time spent executing in kernel mode15- pub system: Time,16-}18+ pub time_system: Time,19 18-pub struct CPUTimer {19- start_cpu: CPUTimes,20+ /// Maximum amount of memory used by the process, in bytes21+ pub memory_usage: Information,22 }23 22-impl CPUTimer {23- pub fn start() -> Self {24- CPUTimer {25- start_cpu: get_cpu_times(),26- }27- }24+#[allow(clippy::useless_conversion)]25+fn convert_timeval(tv: libc::timeval) -> Time {26+ let sec = tv.tv_sec as f64;27+ let usec = tv.tv_usec as f64;28 29- pub fn stop(&self) -> (Time, Time, Information) {30- let end_cpu = get_cpu_times();31- let cpu_interval = cpu_time_interval(&self.start_cpu, &end_cpu);32- (33- cpu_interval.user,34- cpu_interval.system,35- Information::new::<byte>(end_cpu.memory_usage_byte as f64),36- )37- }29+ Time::new::<second>(sec) + Time::new::<microsecond>(usec)30 }31 40-/// Read CPU execution times ('user' and 'system')41-fn get_cpu_times() -> CPUTimes {42- use libc::{getrusage, rusage, RUSAGE_CHILDREN};32+#[allow(clippy::useless_conversion)]33+fn wait4(mut child: Child) -> io::Result<(ExitStatus, ResourceUsage)> {34+ drop(child.stdin.take());35 44- let result: rusage = unsafe {45- let mut buf = mem::zeroed();46- let success = getrusage(RUSAGE_CHILDREN, &mut buf);47- assert_eq!(0, success);48- buf49- };36+ let pid = child.id() as i32;37+ let mut status = 0;38+ let mut rusage = MaybeUninit::zeroed();39 51- const MICROSEC_PER_SEC: i64 = 1000 * 1000;40+ loop {41+ let result = unsafe { libc::wait4(pid, &mut status, 0, rusage.as_mut_ptr()) };42+ if result >= 0 {43+ break;44+ }45+ let error = io::Error::last_os_error();46+ if error.kind() != io::ErrorKind::Interrupted {47+ return Err(error);48+ }49+ }50 53- // Linux and *BSD return the value in KibiBytes, Darwin flavors in bytes54- let max_rss_byte = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {55- result.ru_maxrss51+ let rusage = unsafe { rusage.assume_init() };52+53+ let memory_usage_byte = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {54+ // Linux and *BSD return the value in KibiBytes, Darwin flavors in bytes55+ // A f64 can represent integers up to 2^53 exactly, so we can represent56+ // all values up to 2^53 bytes = 8 PiB exactly. Beyond that, our precision57+ // is larger than 1 byte, but that's considered acceptable.58+ Information::new::<byte>(rusage.ru_maxrss as f64)59 } else {57- result.ru_maxrss * 102460+ Information::new::<kibibyte>(rusage.ru_maxrss as f64)61 };62 60- #[allow(clippy::useless_conversion)]61- CPUTimes {62- user_usec: i64::from(result.ru_utime.tv_sec) * MICROSEC_PER_SEC63- + i64::from(result.ru_utime.tv_usec),64- system_usec: i64::from(result.ru_stime.tv_sec) * MICROSEC_PER_SEC65- + i64::from(result.ru_stime.tv_usec),66- memory_usage_byte: u64::try_from(max_rss_byte).unwrap_or(0),67- }63+ Ok((64+ ExitStatus::from_raw(status),65+ ResourceUsage {66+ time_user: convert_timeval(rusage.ru_utime),67+ time_system: convert_timeval(rusage.ru_stime),68+ memory_usage: memory_usage_byte.into(),69+ },70+ ))71 }72 70-/// Compute the time intervals in between two `CPUTimes` snapshots71-fn cpu_time_interval(start: &CPUTimes, end: &CPUTimes) -> CPUInterval {72- CPUInterval {73- user: Time::new::<microsecond>((end.user_usec - start.user_usec) as f64),74- system: Time::new::<microsecond>((end.system_usec - start.system_usec) as f64),73+pub struct CPUTimer {}74+75+impl CPUTimer {76+ pub fn start() -> Self {77+ Self {}78 }76-}79 78-#[cfg(test)]79-use crate::quantity::second;80-#[cfg(test)]81-use approx::assert_relative_eq;82-83-#[test]84-fn test_cpu_time_interval() {85- let t_a = CPUTimes {86- user_usec: 12345,87- system_usec: 54321,88- memory_usage_byte: 0,89- };90-91- let t_b = CPUTimes {92- user_usec: 20000,93- system_usec: 70000,94- memory_usage_byte: 0,95- };96-97- let t_zero = cpu_time_interval(&t_a, &t_a);98- assert!(t_zero.user.get::<second>().abs() < f64::EPSILON);99- assert!(t_zero.system.get::<second>().abs() < f64::EPSILON);100-101- let t_ab = cpu_time_interval(&t_a, &t_b);102- assert_relative_eq!(0.007655, t_ab.user.get::<second>());103- assert_relative_eq!(0.015679, t_ab.system.get::<second>());104-105- let t_ba = cpu_time_interval(&t_b, &t_a);106- assert_relative_eq!(-0.007655, t_ba.user.get::<second>());107- assert_relative_eq!(-0.015679, t_ba.system.get::<second>());80+ pub fn stop(&self, child: Child) -> Result<(Time, Time, Information, ExitStatus)> {81+ let (status, usage) = wait4(child)?;82+ Ok((83+ usage.time_user,84+ usage.time_system,85+ usage.memory_usage,86+ status,87+ ))88+ }89 }