/// Sends CPU usage in percent via channel every duration (sends nothing during first duration)
Sends CPU usage in percent via channel every duration (sends nothing during first duration)
Sends CPU usage in percent via channel every duration ( sends nothing during first duration )
pub fn cpu_usage(duration: Duration) -> (Receiver<f64>, JoinHandle<Result<(), Fail>>) {
    // create channel
    let (tx, rc): (Sender<f64>, Receiver<f64>) = channel();
    // spawn sender thread
    let thread = spawn(move || {
        // read first cpu times and wait first second
        let (mut prev_idle, mut prev_total) = read_cpu_times()?;
        sleep(duration);
        // send cpu usage continously
        loop {
            // read cpu times and calculate difference
            let (idle, total) = read_cpu_times()?;
            let dif_idle = (idle - prev_idle) as f64;
            let dif_total = (total - prev_total) as f64;
            // calculate cpu usage and send
            let cpu_usage = ((1.0 - dif_idle / dif_total) * 10000.0).round() / 100.0;
            tx.send(cpu_usage).or_else(Fail::from)?;
            // set previous times and wait next second
            prev_idle = idle;
            prev_total = total;
            sleep(duration);
        }
    });
    // return receiver and thread
    (rc, thread)
}
pub fn cpu_usage ( duration : Duration ) -> ( Receiver < f64 > , JoinHandle < Result < ( ) , Fail > > ) { // create channel let ( tx , rc ) : ( Sender < f64 > , Receiver < f64 > ) = channel ( ) ; // spawn sender thread let thread = spawn ( move | | { // read first cpu times and wait first second let ( mut prev_idle , mut prev_total ) = read_cpu_times ( ) ? ; sleep ( duration ) ; // send cpu usage continously loop { // read cpu times and calculate difference let ( idle , total ) = read_cpu_times ( ) ? ; let dif_idle = ( idle - prev_idle ) as f64 ; let dif_total = ( total - prev_total ) as f64 ; // calculate cpu usage and send let cpu_usage = ( ( 1.0 - dif_idle / dif_total ) * 10000.0 ) . round ( ) / 100.0 ; tx . send ( cpu_usage ) . or_else ( Fail :: from ) ? ; // set previous times and wait next second prev_idle = idle ; prev_total = total ; sleep ( duration ) ; } } ) ; // return receiver and thread ( rc , thread ) }
Sends CPU usage in percent via channel every duration (sends nothing during first duration)
Sends CPU usage in percent via channel every duration ( sends nothing during first duration )
duration
Duration