I'm trying to test the efficiency of parts of my code, and C++ has a clock
function in ctime
that allows measurement of the processor time consumed by the program using the clock_t
type. Is there some Rust equivalent that isn't just measuring the absolute time between two points in the code?
Asked
Active
Viewed 1,536 times
7

WiSaGaN
- 46,887
- 10
- 54
- 88

Harvey Adcock
- 929
- 1
- 7
- 16
-
What's wrong with a high resolution timer like https://doc.rust-lang.org/time/time/fn.precise_time_ns.html ? – oli_obk Apr 19 '16 at 11:44
-
2`libc` crate, `clock` function – набиячлэвэли Apr 19 '16 at 11:44
-
2@Ker , OP is asking about user cpu time, not wall clock time. – WiSaGaN Apr 19 '16 at 11:51
-
@ker as far as I can tell from the documentation (it's very brief!) doesn't this just tell you an exact time and from that you can work out a difference in times? Unlike the `clock` function which uses how much time the processor has been running on the process? – Harvey Adcock Apr 19 '16 at 11:52
2 Answers
5
If it's required to use clock
, then you will need to add a bit of a shim. At least on OS X, it appears that libc doesn't expose clock
, but it does give you clock_t
(which is the harder part of the equation). Exposing clock
is then straight-forward:
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'd probably make a wrapper that marks clock
as safe to call in any circumstance though.

Shepmaster
- 388,571
- 95
- 1,107
- 1,366
-
2Know any reason why `libc` does not include `clock`. `clock` seems to be in `C` stdlib. – WiSaGaN Apr 22 '16 at 08:05
3
I've been 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;
}

malbarbo
- 10,717
- 1
- 42
- 57