Debian Codegraph @

src/uu/basenc/benches/basenc_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 //! Base16 output benchmarks.
7
8 #[cfg(unix)]
9 mod benches {
10 use divan::{Bencher, black_box};
11 use std::fs::File;
12 use uu_basenc::uumain;
13 use uucore::benchmark::{run_util_function, setup_test_file};
14
15 const INPUT_SIZE: usize = 16 * 1024 * 1024;
16 const ENCODED_SIZE: usize = INPUT_SIZE * 2;
17 const OUTPUT_SIZE: u64 =
18 (ENCODED_SIZE + ENCODED_SIZE.div_ceil(uu_base32::base_common::WRAP_DEFAULT)) as u64;
19
20 fn input_file() -> std::path::PathBuf {
21 setup_test_file(&vec![0xA5; INPUT_SIZE])
22 }
23
24 fn redirect_stdout(output: &File) -> rustix::fd::OwnedFd {
25 let stdout_backup = rustix::io::dup(rustix::stdio::stdout()).unwrap();
26 rustix::stdio::dup2_stdout(output).unwrap();
27 stdout_backup
28 }
29
30 fn restore_stdout(stdout_backup: &rustix::fd::OwnedFd) {
31 rustix::stdio::dup2_stdout(stdout_backup).unwrap();
32 }
33
34 /// Encode Base16 to `/dev/null`.
35 #[divan::bench]
36 fn base16_encode_to_dev_null(bencher: Bencher) {
37 let input_path = input_file();
38 let input = input_path.to_str().unwrap();
39 let dev_null = std::fs::OpenOptions::new()
40 .write(true)
41 .open("/dev/null")
42 .unwrap();
43 let stdout_backup = redirect_stdout(&dev_null);
44
45 assert_eq!(run_util_function(uumain, &["--base16", input]), 0);
46
47 bencher.bench_local(|| {
48 black_box(run_util_function(uumain, &["--base16", input]));
49 });
50
51 restore_stdout(&stdout_backup);
52 }
53
54 /// Encode Base16 to a file.
55 #[divan::bench]
56 fn base16_encode_to_file(bencher: Bencher) {
57 let input_path = input_file();
58 let input = input_path.to_str().unwrap();
59 let output = tempfile::tempfile().unwrap();
60 let stdout_backup = redirect_stdout(&output);
61
62 assert_eq!(run_util_function(uumain, &["--base16", input]), 0);
63 assert_eq!(output.metadata().unwrap().len(), OUTPUT_SIZE);
64
65 bencher
66 .with_inputs(|| {
67 output.set_len(0).unwrap();
68 rustix::fs::seek(&output, rustix::fs::SeekFrom::Start(0)).unwrap();
69 })
70 .bench_local_values(|()| {
71 black_box(run_util_function(uumain, &["--base16", input]));
72 });
73
74 restore_stdout(&stdout_backup);
75 }
76 }
77
78 fn main() {
79 divan::main();
80 }