Skip to content

Commit f69dacb

Browse files
Alexandra Iordacheacatangiu
authored andcommitted
fc_util: add function that gets current CPU time
This is esentially a wrapper over libc::clock_gettime, because neither the time nor the chrono crate offer an implementation of clock_gettime for CPU time. Signed-off-by: Alexandra Iordache <[email protected]>
1 parent c632227 commit f69dacb

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

fc_util/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ version = "0.1.0"
44
authors = ["Amazon firecracker team <[email protected]>"]
55

66
[dependencies]
7+
libc = ">=0.2.39"
78
time = ">=0.1.39"
89
timerfd = "1.0"
910

fc_util/src/lib.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
extern crate libc;
2+
13
#[macro_use]
24
extern crate logger;
35

@@ -10,6 +12,20 @@ pub fn timestamp_cycles() -> u64 {
1012
unsafe { std::arch::x86_64::_rdtsc() as u64 }
1113
}
1214

15+
fn timespec_to_us(time_struct: &libc::timespec) -> u64 {
16+
(time_struct.tv_sec as u64) * 1_000_000 + (time_struct.tv_nsec as u64) / 1000
17+
}
18+
19+
pub fn now_cputime_us() -> u64 {
20+
let mut time_struct = libc::timespec {
21+
tv_sec: 0,
22+
tv_nsec: 0,
23+
};
24+
// Safe because the parameters are valid.
25+
unsafe { libc::clock_gettime(libc::CLOCK_PROCESS_CPUTIME_ID, &mut time_struct) };
26+
timespec_to_us(&time_struct)
27+
}
28+
1329
#[cfg(test)]
1430
mod tests {
1531
use super::*;
@@ -20,4 +36,11 @@ mod tests {
2036
assert!(timestamp_cycles() < timestamp_cycles());
2137
}
2238
}
39+
40+
#[test]
41+
fn test_now_cputime_us() {
42+
for _ in 0..1000 {
43+
assert!(now_cputime_us() <= now_cputime_us());
44+
}
45+
}
2346
}

0 commit comments

Comments
 (0)