Skip to content
Myr

windows_timer.rs

This file

Path

src/timer/windows_timer.rs

83 lines · 2.3 KiB · Rust

Last changed by

Re-order importsDavid Peterbefore adoption9df6174

History of this file

Take 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 super::internal::CPUTimes;11use crate::timer::{TimerStart, TimerStop};12use crate::units::Second;1314const HUNDRED_NS_PER_MS: i64 = 10;1516pub fn get_cpu_timer(process: &Child) -> Box<dyn TimerStop<Result = (Second, Second)>> {17    Box::new(CPUTimer::start_for_process(process))18}1920struct CPUTimer {21    handle: RawHandle,22}2324impl TimerStart for CPUTimer {25    fn start() -> Self {26        panic!()27    }2829    fn start_for_process(process: &Child) -> Self {30        CPUTimer {31            handle: process.as_raw_handle(),32        }33    }34}3536impl TimerStop for CPUTimer {37    type Result = (Second, Second);3839    fn stop(&self) -> Self::Result {40        let times = get_cpu_times(self.handle);41        (42            times.user_usec as f64 * 1e-6,43            times.system_usec as f64 * 1e-6,44        )45    }46}4748/// Read CPU execution times (dummy for now)49fn get_cpu_times(handle: RawHandle) -> CPUTimes {50    let (user_usec, system_usec) = unsafe {51        let mut _ctime = mem::zeroed();52        let mut _etime = mem::zeroed();53        let mut kernel_time = mem::zeroed();54        let mut user_time = mem::zeroed();55        let res = GetProcessTimes(56            handle as HANDLE,57            &mut _ctime,58            &mut _etime,59            &mut kernel_time,60            &mut user_time,61        );6263        // GetProcessTimes will exit with non-zero if success as per: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx64        if res != 0 {65            // Extract times as laid out here: https://support.microsoft.com/en-us/help/188768/info-working-with-the-filetime-structure66            // Both user_time and kernel_time are spans that the proces spent in either.67            let user: i64 = (((user_time.dwHighDateTime as i64) << 32)68                + user_time.dwLowDateTime as i64)69                / HUNDRED_NS_PER_MS;70            let kernel: i64 = (((kernel_time.dwHighDateTime as i64) << 32)71                + kernel_time.dwLowDateTime as i64)72                / HUNDRED_NS_PER_MS;73            (user, kernel)74        } else {75            (0, 0)76        }77    };7879    CPUTimes {80        user_usec,81        system_usec,82    }83}