Is there a Rust equivalent clock function in C ++?

I am trying to check the efficiency of parts of my code, and C ++ has a clock function in ctime that allows ctime to measure the processor time consumed by the program using the clock_t type. Is there some sort of Rust equivalent that doesn't just measure the absolute time between two points in code?

+6
source share
2 answers

If for < is required To use clock , you need to add a bit of padding. At least on OS X, libc doesn't seem to set the clock , but it does give you clock_t (which is the more complicated part of the equation). The clock display is straightforward:

 extern crate libc; mod ffi { extern { pub fn clock() -> ::libc::clock_t; } } fn main() { let start = unsafe { ffi::clock() }; let mut dummy = 0; for i in 0..20000 { dummy += i }; let end = unsafe { ffi::clock() }; println!("{}, {}, {}, {}", dummy, start, end, end - start); } 

I would probably do a wrapper that marks clock as safe to call under any circumstances.

+5
source

I am using this code:

 extern crate libc; use std::mem; use std::io; use std::time::Duration; pub fn cpu_time() -> Duration { unsafe { let mut tp = mem::uninitialized(); if sys::clock_gettime(sys::CLOCK_PROCESS_CPUTIME_ID, &mut tp) == 0 { Duration::new(tp.tv_sec as u64, tp.tv_nsec as u32) } else { panic!("cpu_time: {}", io::Error::last_os_error()); } } } mod sys { use libc::{c_int, timespec}; extern "C" { pub fn clock_gettime(clk_id: c_int, tp: *mut timespec) -> c_int; } pub const CLOCK_PROCESS_CPUTIME_ID: c_int = 2; } 
+3
source

All Articles