Fix user and kernel times on Windows
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Clemens Wasser · committed by David Peter · parent 6c0ec31 · Browse files · 5 files·+121 added−52 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+121 added−52 removed
- other:+121 added−52 removed
Provenance
- Commit
ac8c114- Tree
b53a98e- Author
Clemens Wasser <clemens.wasser@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
6c0ec31
5 files changed+121 added−52 removed
modified:src/timer/mod.rs+15 added-4 removed
19 unmodified lines20 use std::process::{ChildStdout, Command, ExitStatus};21 22 use anyhow::Result;23 24+#[cfg(not(windows))]25 #[derive(Debug, Copy, Clone)]26 struct CPUTimes {27 /// Total amount of time spent executing in user mode28 pub user_usec: i64,45 unmodified lines74 }75 76 /// Execute the given command and return a timing summary77 pub fn execute_and_measure(mut command: Command) -> Result<TimerResult> {77- let wallclock_timer = WallClockTimer::start();78-78 #[cfg(not(windows))]79 let cpu_timer = self::unix_timer::CPUTimer::start();80 81+ #[cfg(windows)]82+ {83+ use std::os::windows::process::CommandExt;84+85+ // Create a suspended process86+ command.creation_flags(4);87+ }88+89+ let wallclock_timer = WallClockTimer::start();90 let mut child = command.spawn()?;91 92 #[cfg(windows)]85- let cpu_timer = self::windows_timer::CPUTimer::start_for_process(&child);93+ let cpu_timer = {94+ // SAFETY: We created a suspended process95+ unsafe { self::windows_timer::CPUTimer::start_suspended_process(&child) }96+ };97 98 if let Some(output) = child.stdout.take() {99 // Handle CommandOutputPolicy::Pipe100 discard(output);101 }102 103 let status = child.wait()?;104 94- let (time_user, time_system) = cpu_timer.stop();105 let time_real = wallclock_timer.stop();106+ let (time_user, time_system) = cpu_timer.stop();107 108 Ok(TimerResult {109 time_real,110 time_user,4 unmodified linesmodified:src/timer/windows_timer.rs+92 added-45 removed
1 #![cfg(windows)]2+#![warn(unsafe_op_in_unsafe_fn)]3 3-use std::mem;4-use std::os::windows::io::{AsRawHandle, RawHandle};5-use std::process::Child;4+use std::{mem, os::windows::io::AsRawHandle, process, ptr};5 7-use winapi::um::processthreadsapi::GetProcessTimes;8-use winapi::um::winnt::HANDLE;6+use clap::__macro_refs::once_cell::sync::Lazy;7+use winapi::{8+ shared::{ntdef::NTSTATUS, ntstatus::STATUS_SUCCESS},9+ um::{10+ handleapi::CloseHandle,11+ jobapi2::{AssignProcessToJobObject, CreateJobObjectW, QueryInformationJobObject},12+ libloaderapi::{GetModuleHandleA, GetProcAddress},13+ winnt::{14+ JobObjectBasicAccountingInformation, HANDLE, JOBOBJECT_BASIC_ACCOUNTING_INFORMATION,15+ },16+ },17+};18 10-use crate::timer::CPUTimes;19+#[cfg(windows_process_extensions_main_thread_handle)]20+use winapi::shared::minwindef::DWORD;21+22 use crate::util::units::Second;23 24 const HUNDRED_NS_PER_MS: i64 = 10;25 26+#[allow(non_upper_case_globals)]27+static NtResumeProcess: Lazy<unsafe extern "system" fn(ProcessHandle: HANDLE) -> NTSTATUS> =28+ Lazy::new(|| {29+ // SAFETY: Getting the module handle for ntdll.dll is safe30+ let ntdll = unsafe { GetModuleHandleA(b"ntdll.dll\0".as_ptr().cast()) };31+ assert!(!ntdll.is_null(), "GetModuleHandleA failed");32+33+ // SAFETY: The ntdll handle is valid34+ let nt_resume_process =35+ unsafe { GetProcAddress(ntdll, b"NtResumeProcess\0".as_ptr().cast()) };36+ assert!(!nt_resume_process.is_null(), "GetProcAddress failed");37+38+ // SAFETY: We transmute to the correct function signature39+ unsafe { mem::transmute(nt_resume_process) }40+ });41+42 pub struct CPUTimer {16- handle: RawHandle,43+ job_object: HANDLE,44 }45 46 impl CPUTimer {20- pub fn start_for_process(process: &Child) -> Self {21- CPUTimer {22- handle: process.as_raw_handle(),47+ pub unsafe fn start_suspended_process(child: &process::Child) -> Self {48+ // SAFETY: Creating a new job object is safe49+ let job_object = unsafe { CreateJobObjectW(ptr::null_mut(), ptr::null_mut()) };50+ assert!(!job_object.is_null(), "CreateJobObjectW failed");51+52+ // SAFETY: The job object handle is valid53+ let ret = unsafe { AssignProcessToJobObject(job_object, child.as_raw_handle()) };54+ assert!(ret != 0, "AssignProcessToJobObject failed");55+56+ #[cfg(windows_process_extensions_main_thread_handle)]57+ {58+ // SAFETY: The main thread handle is valid59+ let ret = unsafe { ResumeThread(child.main_thread_handle().as_raw_handle()) };60+ assert!(ret != -1 as DWORD, "NtResumeProcess failed");61 }62+63+ #[cfg(not(windows_process_extensions_main_thread_handle))]64+ {65+ // Since we can't get the main thread handle on stable rust, we use66+ // the undocumented but widely known `NtResumeProcess` function to67+ // resume a process by it's handle.68+69+ // SAFETY: The process handle is valid70+ let ret = unsafe { NtResumeProcess(child.as_raw_handle()) };71+ assert!(ret == STATUS_SUCCESS, "NtResumeProcess failed");72+ }73+74+ Self { job_object }75 }76 77 pub fn stop(&self) -> (Second, Second) {27- let times = get_cpu_times(self.handle);28- (29- times.user_usec as f64 * 1e-6,30- times.system_usec as f64 * 1e-6,31- )32- }33-}78+ let mut job_object_info =79+ mem::MaybeUninit::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>::uninit();80 35-/// Read CPU execution times36-fn get_cpu_times(handle: RawHandle) -> CPUTimes {37- let (user_usec, system_usec) = {38- let mut _ctime = unsafe { mem::zeroed() };39- let mut _etime = unsafe { mem::zeroed() };40- let mut kernel_time = unsafe { mem::zeroed() };41- let mut user_time = unsafe { mem::zeroed() };81+ // SAFETY: A valid job object got created in `start_suspended_process`82 let res = unsafe {43- GetProcessTimes(44- handle as HANDLE,45- &mut _ctime,46- &mut _etime,47- &mut kernel_time,48- &mut user_time,83+ QueryInformationJobObject(84+ self.job_object,85+ JobObjectBasicAccountingInformation,86+ job_object_info.as_mut_ptr().cast(),87+ mem::size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>() as u32,88+ ptr::null_mut(),89 )90 };91 52- // GetProcessTimes will exit with non-zero if success as per: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx92 if res != 0 {54- // Extract times as laid out here: https://support.microsoft.com/en-us/help/188768/info-working-with-the-filetime-structure55- // Both user_time and kernel_time are spans that the process spent in either.56- let user: i64 = (((user_time.dwHighDateTime as i64) << 32)57- + user_time.dwLowDateTime as i64)58- / HUNDRED_NS_PER_MS;59- let kernel: i64 = (((kernel_time.dwHighDateTime as i64) << 32)60- + kernel_time.dwLowDateTime as i64)61- / HUNDRED_NS_PER_MS;62- (user, kernel)93+ // SAFETY: The job object info got correctly initialized94+ let job_object_info = unsafe { job_object_info.assume_init() };95+96+ // SAFETY: The `TotalUserTime` is "The total amount of user-mode execution time for97+ // all active processes associated with the job, as well as all terminated processes no98+ // longer associated with the job, in 100-nanosecond ticks." and is safe to extract99+ let user: i64 = unsafe { job_object_info.TotalUserTime.QuadPart() } / HUNDRED_NS_PER_MS;100+101+ // SAFETY: The `TotalKernelTime` is "The total amount of kernel-mode execution time102+ // for all active processes associated with the job, as well as all terminated103+ // processes no longer associated with the job, in 100-nanosecond ticks." and is safe104+ // to extract105+ let kernel: i64 =106+ unsafe { job_object_info.TotalKernelTime.QuadPart() } / HUNDRED_NS_PER_MS;107+ (user as f64 * 1e-6, kernel as f64 * 1e-6)108 } else {64- (0, 0)109+ (0.0, 0.0)110 }66- };111+ }112+}113 68- CPUTimes {69- user_usec,70- system_usec,114+impl Drop for CPUTimer {115+ fn drop(self: &mut Self) {116+ // SAFETY: A valid job object got created in `start_suspended_process`117+ unsafe { CloseHandle(self.job_object) };118 }119 }modified:src/main.rs+5 added
1+#![cfg_attr(2+ all(windows, feature = "windows_process_extensions_main_thread_handle"),3+ feature(windows_process_extensions_main_thread_handle)4+)]5+6 use std::env;7 8 use benchmark::scheduler::Scheduler;9 use cli::get_cli_arguments;47 unmodified linesmodified:Cargo.lock+3 added-2 removed
273 unmodified lines274 "csv",275 "indicatif",276 "libc",277 "nix",278+ "once_cell",279 "predicates",280 "rand 0.8.5",281 "rust_decimal",282 "serde",186 unmodified lines469 checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"470 471 [[package]]472 name = "once_cell"472-version = "1.12.0"473+version = "1.13.1"474 source = "registry+https://github.com/rust-lang/crates.io-index"474-checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225"475+checksum = "074864da206b4973b84eb91683020dbefd6a8c3f0f38e054d93954e891935e4e"476 477 [[package]]478 name = "os_str_bytes"479 version = "6.1.0"443 unmodified linesmodified:Cargo.toml+6 added-1 removed
9 unmodified lines10111213141516171819202110 unmodified lines323334353236373839404118 unmodified lines9 unmodified linesversion = "1.14.0"edition = "2018"build = "build.rs"
[features]# Use the nightly feature windows_process_extensions_main_thread_handlewindows_process_extensions_main_thread_handle = []
[dependencies]colored = "2.0"indicatif = "0.16"statistical = "1.0"10 unmodified lines[target.'cfg(not(windows))'.dependencies]libc = "0.2"
[target.'cfg(windows)'.dependencies]winapi = { version = "0.3", features = ["processthreadsapi", "minwindef", "winnt"] }winapi = { version = "0.3", features = ["processthreadsapi", "minwindef", "winnt", "jobapi2", "tlhelp32"] }once_cell = "1.13"
[target.'cfg(target_os="linux")'.dependencies]nix = { version = "0.24.2", features = ["zerocopy"] }
18 unmodified lines