Repository navigation
Expand file tree
/
Copy pathtime.rs
More file actions
100 lines (87 loc) · 2.49 KB
/
Copy pathtime.rs
File metadata and controls
100 lines (87 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//! Run with:
//!
//! ```sh
//! cargo bench -q -p examples --bench time
//! ```
use std::time::{Instant, SystemTime};
use divan::Bencher;
fn main() {
divan::main();
}
mod now {
use super::*;
#[divan::bench]
fn instant() -> Instant {
Instant::now()
}
#[divan::bench]
fn system_time() -> SystemTime {
SystemTime::now()
}
#[divan::bench(name = if cfg!(target_arch = "aarch64") {
"tsc (aarch64)"
} else {
"tsc (x86)"
})]
#[cfg(all(
not(miri),
any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64"),
))]
pub fn tsc() -> u64 {
#[cfg(target_arch = "aarch64")]
unsafe {
let timestamp: u64;
std::arch::asm!(
"mrs {}, cntvct_el0",
out(reg) timestamp,
// Leave off `nomem` because this should be a compiler fence.
options(nostack, preserves_flags),
);
timestamp
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
unsafe {
#[cfg(target_arch = "x86")]
use std::arch::x86;
#[cfg(target_arch = "x86_64")]
use std::arch::x86_64 as x86;
x86::_rdtsc()
}
}
}
mod duration_since {
use super::*;
#[divan::bench]
fn instant(bencher: Bencher) {
bencher
.with_inputs(|| [Instant::now(), Instant::now()])
.bench_values(|[start, end]| end.duration_since(start));
}
#[divan::bench]
fn system_time(bencher: Bencher) {
bencher
.with_inputs(|| [SystemTime::now(), SystemTime::now()])
.bench_values(|[start, end]| end.duration_since(start));
}
#[divan::bench(name = if cfg!(target_arch = "aarch64") {
"tsc (aarch64)"
} else {
"tsc (x86)"
})]
#[cfg(all(
not(miri),
any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64"),
))]
fn tsc(bencher: Bencher) {
bencher.with_inputs(|| [crate::now::tsc(), crate::now::tsc()]).bench_values(
|[start, end]| {
// Simply subtract because an optimized timing implementation
// would want to keep the value as TSC units for as long as
// possible before dividing by the TSC frequency.
//
// Saturating arithmetic to ensures monotonicity.
end.saturating_sub(start)
},
)
}
}