Debian Codegraph @

src/uu/tr/benches/tr_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 // spell-checker:ignore aeiou
7
8 //! Benchmarks for `tr`.
9 //!
10 //! `tr` only reads stdin, so each bench redirects fd 0 onto a prepared
11 //! input file before invoking `uumain`. fd 1 is redirected to /dev/null
12 //! so the translated output does not flood the harness's terminal.
13 //! Both fds are restored after each iteration.
14
15 #[cfg(unix)]
16 mod benches {
17 use divan::{Bencher, black_box};
18 use uu_tr::uumain;
19 use uucore::benchmark::{run_util_function, setup_test_file, text_data};
20
21 fn bench_tr_with_stdin(bencher: Bencher, data: &[u8], args: &[&str]) {
22 let file_path = setup_test_file(data);
23 let file = std::fs::File::open(file_path).unwrap();
24 let devnull = std::fs::OpenOptions::new()
25 .write(true)
26 .open("/dev/null")
27 .unwrap();
28 let stdin_bak = rustix::io::dup(rustix::stdio::stdin()).unwrap();
29 let stdout_bak = rustix::io::dup(rustix::stdio::stdout()).unwrap();
30
31 bencher.bench_local(|| {
32 use rustix::stdio::{dup2_stdin, dup2_stdout};
33 rustix::fs::seek(&file, rustix::fs::SeekFrom::Start(0)).unwrap();
34 dup2_stdin(&file).unwrap();
35 dup2_stdout(&devnull).unwrap();
36 black_box(run_util_function(uumain, args));
37 dup2_stdin(&stdin_bak).unwrap();
38 dup2_stdout(&stdout_bak).unwrap();
39 });
40 }
41
42 const SIZE_MB: usize = 16;
43
44 /// ASCII lowercase->uppercase range translation.
45 /// Exercises the AVX2 ASCII-range fast path on x86_64 hosts that
46 /// support it, and the scalar range fallback on other targets.
47 #[divan::bench]
48 fn tr_ascii_range_lower_to_upper(bencher: Bencher) {
49 let data = text_data::generate_by_size(SIZE_MB, 80);
50 bench_tr_with_stdin(bencher, &data, &["a-z", "A-Z"]);
51 }
52
53 /// Single-character replacement. Exercises the existing
54 /// `process_single_char_replace` SIMD path; guards against
55 /// regressions outside the new range fast path.
56 #[divan::bench]
57 fn tr_single_char_replace(bencher: Bencher) {
58 let data = text_data::generate_by_size(SIZE_MB, 80);
59 bench_tr_with_stdin(bencher, &data, &["a", "b"]);
60 }
61
62 /// Multi-character set translation. Falls through to the
63 /// 256-byte translation table path (no fast path applies).
64 #[divan::bench]
65 fn tr_multi_char_translate(bencher: Bencher) {
66 let data = text_data::generate_by_size(SIZE_MB, 80);
67 bench_tr_with_stdin(bencher, &data, &["aeiou", "AEIOU"]);
68 }
69
70 /// Delete an ASCII range — covers the deletion path.
71 #[divan::bench]
72 fn tr_delete_ascii_range(bencher: Bencher) {
73 let data = text_data::generate_by_size(SIZE_MB, 80);
74 bench_tr_with_stdin(bencher, &data, &["-d", "a-z"]);
75 }
76 }
77
78 fn main() {
79 divan::main();
80 }