Skip to content
Myr

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

3 files+73 added−97 removed

modified:src/quantity/mod.rs+3 added-1 removed
1 unmodified line
23pub use uom::num_traits::Zero;4pub use uom::si::f64::{Information, Ratio, Time};5pub use uom::si::information::byte;6#[cfg(any(not(windows), test))]7pub use uom::si::information::kibibyte;8pub use uom::si::ratio::ratio;9#[cfg(any(not(windows), test))]10pub use uom::si::time::microsecond;11pub use uom::si::time::{nanosecond, second};
44 unmodified lines
56 }57}5859#[cfg(test)]58use uom::si::{information::kibibyte, time::millisecond};60use uom::si::time::millisecond;6162#[test]63fn test_time() {64 let time = Time::new::<millisecond>(123.4);
73 unmodified lines
modified:src/timer/mod.rs+6 added-13 removed
22 unmodified lines
23use std::process::{ChildStdout, Command};2425use anyhow::Result;2627#[cfg(not(windows))]28#[derive(Debug, Copy, Clone)]29struct CPUTimes {30 /// Total amount of time spent executing in user mode31 pub user_usec: i64,3233 /// Total amount of time spent executing in kernel mode34 pub system_usec: i64,3536 /// Maximum amount of memory used by the process, in bytes37 pub memory_usage_byte: u64,38}3927/// Discard the output of a child process.28fn discard(output: ChildStdout) {29 const CHUNK_SIZE: usize = 64 << 10;30
50 unmodified lines
81 // Handle CommandOutputPolicy::Pipe82 discard(output);83 }8485 #[cfg(not(windows))]86 let (time_user, time_system, peak_memory_usage, exit_status) = cpu_timer.stop(child)?;8788 #[cfg(windows)]89 let exit_status = child.wait()?;9091 let time_wall_clock = wallclock_timer.stop();9293 #[cfg(windows)]94 let (time_user, time_system, peak_memory_usage) = cpu_timer.stop();9596 Ok(Measurement {97 time_wall_clock,
6 unmodified lines
modified:src/timer/unix_timer.rs+64 added-83 removed
1#![cfg(not(windows))]23use std::convert::TryFrom;4use std::mem;3use std::io;4use std::mem::MaybeUninit;5use std::os::unix::process::ExitStatusExt;6use std::process::{Child, ExitStatus};76use crate::quantity::{byte, microsecond, Information, Time};7use crate::timer::CPUTimes;8use anyhow::Result;910use crate::quantity::{byte, kibibyte, microsecond, second, Information, Time};1112#[derive(Debug, Copy, Clone)]10pub struct CPUInterval {13struct ResourceUsage {14 /// Total amount of time spent executing in user mode12 pub user: Time,15 pub time_user: Time,1617 /// Total amount of time spent executing in kernel mode15 pub system: Time,16}18 pub time_system: Time,1918pub struct CPUTimer {19 start_cpu: CPUTimes,20 /// Maximum amount of memory used by the process, in bytes21 pub memory_usage: Information,22}2322impl CPUTimer {23 pub fn start() -> Self {24 CPUTimer {25 start_cpu: get_cpu_times(),26 }27 }24#[allow(clippy::useless_conversion)]25fn convert_timeval(tv: libc::timeval) -> Time {26 let sec = tv.tv_sec as f64;27 let usec = tv.tv_usec as f64;2829 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}3140/// Read CPU execution times ('user' and 'system')41fn get_cpu_times() -> CPUTimes {42 use libc::{getrusage, rusage, RUSAGE_CHILDREN};32#[allow(clippy::useless_conversion)]33fn wait4(mut child: Child) -> io::Result<(ExitStatus, ResourceUsage)> {34 drop(child.stdin.take());3544 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();3951 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 }5053 // 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() };5253 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 };6260 #[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}7270/// Compute the time intervals in between two `CPUTimes` snapshots71fn 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),73pub struct CPUTimer {}7475impl CPUTimer {76 pub fn start() -> Self {77 Self {}78 }76}7978#[cfg(test)]79use crate::quantity::second;80#[cfg(test)]81use approx::assert_relative_eq;8283#[test]84fn test_cpu_time_interval() {85 let t_a = CPUTimes {86 user_usec: 12345,87 system_usec: 54321,88 memory_usage_byte: 0,89 };9091 let t_b = CPUTimes {92 user_usec: 20000,93 system_usec: 70000,94 memory_usage_byte: 0,95 };9697 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);100101 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>());104105 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}