windows_timer.rs
This file
Path
src/timer/windows_timer.rs
70 lines · 2.0 KiB · Rust
Last changed by
Refactor timer moduleDavid Peterbefore adoptiondefafdf
History of this fileTake it
1#![cfg(windows)]23use std::mem;4use std::os::windows::io::{AsRawHandle, RawHandle};5use std::process::Child;67use winapi::um::processthreadsapi::GetProcessTimes;8use winapi::um::winnt::HANDLE;910use crate::timer::CPUTimes;11use crate::util::units::Second;1213const HUNDRED_NS_PER_MS: i64 = 10;1415pub struct CPUTimer {16 handle: RawHandle,17}1819impl CPUTimer {20 pub fn start_for_process(process: &Child) -> Self {21 CPUTimer {22 handle: process.as_raw_handle(),23 }24 }2526 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}3435/// Read CPU execution times36fn get_cpu_times(handle: RawHandle) -> CPUTimes {37 let (user_usec, system_usec) = unsafe {38 let mut _ctime = mem::zeroed();39 let mut _etime = mem::zeroed();40 let mut kernel_time = mem::zeroed();41 let mut user_time = mem::zeroed();42 let res = GetProcessTimes(43 handle as HANDLE,44 &mut _ctime,45 &mut _etime,46 &mut kernel_time,47 &mut user_time,48 );4950 // GetProcessTimes will exit with non-zero if success as per: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx51 if res != 0 {52 // Extract times as laid out here: https://support.microsoft.com/en-us/help/188768/info-working-with-the-filetime-structure53 // Both user_time and kernel_time are spans that the process spent in either.54 let user: i64 = (((user_time.dwHighDateTime as i64) << 32)55 + user_time.dwLowDateTime as i64)56 / HUNDRED_NS_PER_MS;57 let kernel: i64 = (((kernel_time.dwHighDateTime as i64) << 32)58 + kernel_time.dwLowDateTime as i64)59 / HUNDRED_NS_PER_MS;60 (user, kernel)61 } else {62 (0, 0)63 }64 };6566 CPUTimes {67 user_usec,68 system_usec,69 }70}