Debian Codegraph @

src/uu/timeout/benches/timeout_bench.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 use divan::{Bencher, black_box};
7 use uu_timeout::uumain;
8 use uucore::benchmark::run_util_function;
9
10 /// First-arg marker that re-runs this bench binary as its own child command,
11 /// a portable `sleep`/`true` stand-in (`cargo bench` builds no other binary
12 /// and Windows lacks both in `PATH`).
13 const CHILD_MARKER: &str = "__timeout_bench_child";
14
15 fn self_exe() -> String {
16 std::env::current_exe()
17 .unwrap()
18 .to_string_lossy()
19 .into_owned()
20 }
21
22 /// Benchmark the fast path where the command exits immediately.
23 #[cfg(unix)]
24 #[divan::bench]
25 fn timeout_quick_exit(bencher: Bencher) {
26 bencher.bench(|| {
27 black_box(run_util_function(uumain, &["0.02", "true"]));
28 });
29 }
30
31 /// Benchmark the fast path where the command exits immediately.
32 #[cfg(windows)]
33 #[divan::bench]
34 fn timeout_quick_exit(bencher: Bencher) {
35 let exe = self_exe();
36 bencher.bench(|| {
37 black_box(run_util_function(
38 uumain,
39 &["0.02", &exe, CHILD_MARKER, "0"],
40 ));
41 });
42 }
43
44 /// Benchmark a command that runs longer than the threshold and receives the default signal.
45 #[cfg(unix)]
46 #[divan::bench]
47 fn timeout_enforced(bencher: Bencher) {
48 bencher.bench(|| {
49 black_box(run_util_function(uumain, &["0.02", "sleep", "0.2"]));
50 });
51 }
52
53 /// Benchmark a command that runs longer than the threshold: timer expiry,
54 /// job-object tree kill and exit-code plumbing.
55 #[cfg(windows)]
56 #[divan::bench]
57 fn timeout_enforced(bencher: Bencher) {
58 let exe = self_exe();
59 bencher.bench(|| {
60 black_box(run_util_function(
61 uumain,
62 &["0.02", &exe, CHILD_MARKER, "0.2"],
63 ));
64 });
65 }
66
67 /// Track timeout-firing latency across small durations; a regression from the
68 /// high-resolution timer (100 ns waitable timer on Windows, POSIX interval
69 /// timers on unix) to a coarser wait shows up as a step change across the
70 /// arguments.
71 #[divan::bench(args = ["0.001", "0.005", "0.02"])]
72 fn timer_expiry_latency(bencher: Bencher, duration: &str) {
73 let exe = self_exe();
74 bencher.bench(|| {
75 black_box(run_util_function(
76 uumain,
77 &[duration, &exe, CHILD_MARKER, "5"],
78 ));
79 });
80 }
81
82 fn main() {
83 // When re-invoked with CHILD_MARKER, act as a tiny `sleep` replacement.
84 let mut args = std::env::args().skip(1);
85 if args.next().as_deref() == Some(CHILD_MARKER) {
86 if let Some(secs) = args.next().and_then(|s| s.parse::<f64>().ok())
87 && secs > 0.0
88 {
89 std::thread::sleep(std::time::Duration::from_secs_f64(secs));
90 }
91 return;
92 }
93 divan::main();
94 }