Implement --output={null,pipe,<FILE>}
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fixes #377.
authored by Tavian Barnes · committed by David Peter · parent f75f0a1 · Browse files · 6 files·+129 added−23 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+129 added−23 removed
- other:+129 added−23 removed
Provenance
- Commit
277807c- Tree
42b1dbd- Author
Tavian Barnes <tavianator@tavianator.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
f75f0a1
6 files changed+129 added−23 removed
modified:src/benchmark/executor.rs+4 added-4 removed
34 unmodified lines35 36 fn run_command_and_measure_common(37 mut command: std::process::Command,38 command_failure_action: CmdFailureAction,39- command_output_policy: CommandOutputPolicy,39+ command_output_policy: &CommandOutputPolicy,40 command_name: &str,41 ) -> Result<TimerResult> {42- let (stdout, stderr) = command_output_policy.get_stdout_stderr();42+ let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;43 command.stdin(Stdio::null()).stdout(stdout).stderr(stderr);44 45 command.env(46 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",35 unmodified lines82 ) -> Result<(TimingResult, ExitStatus)> {83 let result = run_command_and_measure_common(84 command.get_command()?,85 command_failure_action.unwrap_or(self.options.command_failure_action),86- self.options.command_output_policy,86+ &self.options.command_output_policy,87 &command.get_command_line(),88 )?;89 90 Ok((44 unmodified lines135 136 let mut result = run_command_and_measure_common(137 command_builder,138 command_failure_action.unwrap_or(self.options.command_failure_action),139- self.options.command_output_policy,139+ &self.options.command_output_policy,140 &command.get_command_line(),141 )?;142 143 // Subtract shell spawning time144 unmodified linesmodified:src/timer/mod.rs+55 added-13 removed
4 unmodified lines5 6 #[cfg(not(windows))]7 mod unix_timer;8 9+#[cfg(target_os = "linux")]10+use nix::fcntl::{splice, SpliceFFlags};11+#[cfg(target_os = "linux")]12+use std::fs::File;13+#[cfg(target_os = "linux")]14+use std::os::unix::io::AsRawFd;15+16+#[cfg(not(target_os = "linux"))]17+use std::io::Read;18+19 use crate::util::units::Second;20 use wall_clock_timer::WallClockTimer;21 12-use std::process::{Command, ExitStatus};22+use std::process::{ChildStdout, Command, ExitStatus};23 24 use anyhow::Result;25 26 #[derive(Debug, Copy, Clone)]15 unmodified lines42 /// The exit status of the process43 pub status: ExitStatus,44 }45 46+/// Discard the output of a child process.47+fn discard(output: ChildStdout) {48+ const CHUNK_SIZE: usize = 64 << 10;49+50+ #[cfg(target_os = "linux")]51+ {52+ if let Ok(file) = File::create("/dev/null") {53+ while let Ok(bytes) = splice(54+ output.as_raw_fd(),55+ None,56+ file.as_raw_fd(),57+ None,58+ CHUNK_SIZE,59+ SpliceFFlags::empty(),60+ ) {61+ if bytes == 0 {62+ break;63+ }64+ }65+ }66+ }67+68+ #[cfg(not(target_os = "linux"))]69+ {70+ let mut output = output;71+ let mut buf = [0; CHUNK_SIZE];72+ while let Ok(bytes) = output.read(&mut buf) {73+ if bytes == 0 {74+ break;75+ }76+ }77+ }78+}79+80 /// Execute the given command and return a timing summary81 pub fn execute_and_measure(mut command: Command) -> Result<TimerResult> {82 let wallclock_timer = WallClockTimer::start();83 40- #[cfg(not(windows))]41- let ((time_user, time_system), status) = {42- let cpu_timer = self::unix_timer::CPUTimer::start();43- let status = command.status()?;44- (cpu_timer.stop(), status)45- };84+ let mut child = command.spawn()?;85+ let output = child.stdout.take();86 87+ #[cfg(not(windows))]88+ let cpu_timer = self::unix_timer::CPUTimer::start();89 #[cfg(windows)]48- let ((time_user, time_system), status) = {49- let mut child = command.spawn()?;50- let cpu_timer = self::windows_timer::CPUTimer::start_for_process(&child);90+ let cpu_timer = self::windows_timer::CPUTimer::start_for_process(&child);51- let status = child.wait()?;91 53- (cpu_timer.stop(), status)54- };92+ if let Some(output) = output {93+ discard(output);94+ }95+ let status = child.wait()?;96 97+ let (time_user, time_system) = cpu_timer.stop();98 let time_real = wallclock_timer.stop();99 100 Ok(TimerResult {101 time_real,5 unmodified linesmodified:src/cli.rs+14 added
258 unmodified lines259 when trying to benchmark output speed.",260 ),261 )262 .arg(263+ Arg::new("output")264+ .long("output")265+ .conflicts_with("show-output")266+ .takes_value(true)267+ .value_name("WHERE")268+ .help(269+ "Control where the output of the benchmark is redirected.\n\n \270+ null: Redirect output to /dev/null (the default).\n\n \271+ pipe: Feed the output through a pipe before discarding it.\n \272+ Useful if the benchmark special-cases /dev/null.\n\n \273+ <FILE>: Write the output to the given file.",274+ ),275+ )276+ .arg(277 Arg::new("command-name")278 .long("command-name")279 .short('n')280 .takes_value(true)18 unmodified linesmodified:src/options.rs+31 added-6 removed
1+use std::fs::File;2+use std::path::PathBuf;3 use std::process::{Command, Stdio};2-use std::{cmp, fmt};4+use std::{cmp, fmt, io};5 6 use anyhow::ensure;7 use atty::Stream;8 use clap::ArgMatches;101 unmodified lines110 }111 }112 113 /// How to handle the output of benchmarked commands112-#[derive(Debug, Clone, Copy, PartialEq)]114+#[derive(Debug, Clone, PartialEq)]115 pub enum CommandOutputPolicy {116 /// Discard all output117 Discard,118 119+ /// Feed output through a pipe before discarding it120+ Pipe,121+122+ /// Redirect output to a file123+ File(PathBuf),124+125 /// Show command output on the terminal126 Forward,127 }128 3 unmodified lines132 }133 }134 135 impl CommandOutputPolicy {128- pub fn get_stdout_stderr(&self) -> (Stdio, Stdio) {129- match self {136+ pub fn get_stdout_stderr(&self) -> io::Result<(Stdio, Stdio)> {137+ let streams = match self {138 CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),139+140+ // Typically only stdout is performance-relevant, so just pipe that141+ CommandOutputPolicy::Pipe => (Stdio::piped(), Stdio::null()),142+143+ CommandOutputPolicy::File(path) => {144+ let file = File::create(&path)?;145+ (file.into(), Stdio::null())146+ }147+148 CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),132- }149+ };150+151+ Ok(streams)152 }153 }154 155 pub enum ExecutorKind {113 unmodified lines269 options.cleanup_command = matches.value_of("cleanup").map(String::from);270 271 options.command_output_policy = if matches.is_present("show-output") {272 CommandOutputPolicy::Forward273+ } else if let Some(output) = matches.value_of("output") {274+ match output {275+ "null" => CommandOutputPolicy::Discard,276+ "pipe" => CommandOutputPolicy::Pipe,277+ path => CommandOutputPolicy::File(path.into()),278+ }279 } else {280 CommandOutputPolicy::Discard281 };282 3 unmodified lines286 Some("nocolor") => OutputStyleOption::NoColor,287 Some("color") => OutputStyleOption::Color,288 Some("none") => OutputStyleOption::Disabled,289 _ => {265- if options.command_output_policy == CommandOutputPolicy::Discard290+ if options.command_output_policy != CommandOutputPolicy::Forward291 && atty::is(Stream::Stdout)292 {293 OutputStyleOption::Full294 } else {98 unmodified linesmodified:Cargo.lock+22 added
272 unmodified lines273 "colored",274 "csv",275 "indicatif",276 "libc",277+ "nix",278 "predicates",279 "rand 0.8.5",280 "rust_decimal",281 "serde",75 unmodified lines357 source = "registry+https://github.com/rust-lang/crates.io-index"358 checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"359 360 [[package]]361+name = "memoffset"362+version = "0.6.5"363+source = "registry+https://github.com/rust-lang/crates.io-index"364+checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce"365+dependencies = [366+ "autocfg 1.1.0",367+]368+369+[[package]]370+name = "nix"371+version = "0.24.1"372+source = "registry+https://github.com/rust-lang/crates.io-index"373+checksum = "8f17df307904acd05aa8e32e97bb20f2a0df1728bbc2d771ae8f9a90463441e9"374+dependencies = [375+ "bitflags",376+ "cfg-if",377+ "libc",378+ "memoffset",379+]380+381+[[package]]382 name = "normalize-line-endings"383 version = "0.3.0"384 source = "registry+https://github.com/rust-lang/crates.io-index"385 checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be"536 unmodified linesmodified:Cargo.toml+3 added
29 unmodified lines303132333435363738394014 unmodified lines29 unmodified lines
[target.'cfg(windows)'.dependencies]winapi = { version = "0.3", features = ["processthreadsapi", "minwindef", "winnt"] }
[target.'cfg(target_os="linux")'.dependencies]nix = { version = "0.24.1", features = ["zerocopy"] }
[dependencies.clap]version = "3"default-features = falsefeatures = ["suggestions", "color", "wrap_help", "cargo"]14 unmodified lines