windows_timer.rs
This file
Path
src/timer/windows_timer.rs
82 lines · 2.3 KiB · Rust
Last changed by
Remove timer/internal.rsDavid Peterbefore adoption9d61130
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, TimerStart, TimerStop};11use crate::units::Second;1213const HUNDRED_NS_PER_MS: i64 = 10;1415pub fn get_cpu_timer(process: &Child) -> Box<dyn TimerStop<Result = (Second, Second)>> {16 Box::new(CPUTimer::start_for_process(process))17}1819struct CPUTimer {20 handle: RawHandle,21}2223impl TimerStart for CPUTimer {24 fn start() -> Self {25 panic!()26 }2728 fn start_for_process(process: &Child) -> Self {29 CPUTimer {30 handle: process.as_raw_handle(),31 }32 }33}3435impl TimerStop for CPUTimer {36 type Result = (Second, Second);3738 fn stop(&self) -> Self::Result {39 let times = get_cpu_times(self.handle);40 (41 times.user_usec as f64 * 1e-6,42 times.system_usec as f64 * 1e-6,43 )44 }45}4647/// Read CPU execution times (dummy for now)48fn get_cpu_times(handle: RawHandle) -> CPUTimes {49 let (user_usec, system_usec) = unsafe {50 let mut _ctime = mem::zeroed();51 let mut _etime = mem::zeroed();52 let mut kernel_time = mem::zeroed();53 let mut user_time = mem::zeroed();54 let res = GetProcessTimes(55 handle as HANDLE,56 &mut _ctime,57 &mut _etime,58 &mut kernel_time,59 &mut user_time,60 );6162 // GetProcessTimes will exit with non-zero if success as per: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx63 if res != 0 {64 // Extract times as laid out here: https://support.microsoft.com/en-us/help/188768/info-working-with-the-filetime-structure65 // Both user_time and kernel_time are spans that the proces spent in either.66 let user: i64 = (((user_time.dwHighDateTime as i64) << 32)67 + user_time.dwLowDateTime as i64)68 / HUNDRED_NS_PER_MS;69 let kernel: i64 = (((kernel_time.dwHighDateTime as i64) << 32)70 + kernel_time.dwLowDateTime as i64)71 / HUNDRED_NS_PER_MS;72 (user, kernel)73 } else {74 (0, 0)75 }76 };7778 CPUTimes {79 user_usec,80 system_usec,81 }82}