Skip to content
Myr

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

5 files+121 added−52 removed

modified:src/timer/mod.rs+15 added-4 removed
19 unmodified lines
20use std::process::{ChildStdout, Command, ExitStatus};2122use anyhow::Result;2324#[cfg(not(windows))]25#[derive(Debug, Copy, Clone)]26struct CPUTimes {27 /// Total amount of time spent executing in user mode28 pub user_usec: i64,
45 unmodified lines
74}7576/// Execute the given command and return a timing summary77pub fn execute_and_measure(mut command: Command) -> Result<TimerResult> {77 let wallclock_timer = WallClockTimer::start();7878 #[cfg(not(windows))]79 let cpu_timer = self::unix_timer::CPUTimer::start();8081 #[cfg(windows)]82 {83 use std::os::windows::process::CommandExt;8485 // Create a suspended process86 command.creation_flags(4);87 }8889 let wallclock_timer = WallClockTimer::start();90 let mut child = command.spawn()?;9192 #[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 };9798 if let Some(output) = child.stdout.take() {99 // Handle CommandOutputPolicy::Pipe100 discard(output);101 }102103 let status = child.wait()?;10494 let (time_user, time_system) = cpu_timer.stop();105 let time_real = wallclock_timer.stop();106 let (time_user, time_system) = cpu_timer.stop();107108 Ok(TimerResult {109 time_real,110 time_user,
4 unmodified lines
modified:src/timer/windows_timer.rs+92 added-45 removed
1#![cfg(windows)]2#![warn(unsafe_op_in_unsafe_fn)]33use std::mem;4use std::os::windows::io::{AsRawHandle, RawHandle};5use std::process::Child;4use std::{mem, os::windows::io::AsRawHandle, process, ptr};57use winapi::um::processthreadsapi::GetProcessTimes;8use winapi::um::winnt::HANDLE;6use clap::__macro_refs::once_cell::sync::Lazy;7use 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};1810use crate::timer::CPUTimes;19#[cfg(windows_process_extensions_main_thread_handle)]20use winapi::shared::minwindef::DWORD;2122use crate::util::units::Second;2324const HUNDRED_NS_PER_MS: i64 = 10;2526#[allow(non_upper_case_globals)]27static 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");3233 // 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");3738 // SAFETY: We transmute to the correct function signature39 unsafe { mem::transmute(nt_resume_process) }40 });4142pub struct CPUTimer {16 handle: RawHandle,43 job_object: HANDLE,44}4546impl 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");5152 // SAFETY: The job object handle is valid53 let ret = unsafe { AssignProcessToJobObject(job_object, child.as_raw_handle()) };54 assert!(ret != 0, "AssignProcessToJobObject failed");5556 #[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 }6263 #[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.6869 // SAFETY: The process handle is valid70 let ret = unsafe { NtResumeProcess(child.as_raw_handle()) };71 assert!(ret == STATUS_SUCCESS, "NtResumeProcess failed");72 }7374 Self { job_object }75 }7677 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();8035/// Read CPU execution times36fn 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 };9152 // 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() };9596 // 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;100101 // 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}11368 CPUTimes {69 user_usec,70 system_usec,114impl 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)]56use std::env;78use benchmark::scheduler::Scheduler;9use cli::get_cli_arguments;
47 unmodified lines
modified:Cargo.lock+3 added-2 removed
273 unmodified lines
274 "csv",275 "indicatif",276 "libc",277 "nix",278 "once_cell",279 "predicates",280 "rand 0.8.5",281 "rust_decimal",282 "serde",
186 unmodified lines
469checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"470471[[package]]472name = "once_cell"472version = "1.12.0"473version = "1.13.1"474source = "registry+https://github.com/rust-lang/crates.io-index"474checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225"475checksum = "074864da206b4973b84eb91683020dbefd6a8c3f0f38e054d93954e891935e4e"476477[[package]]478name = "os_str_bytes"479version = "6.1.0"
443 unmodified lines
modified:Cargo.toml+6 added-1 removed