Compare commits

..
17 changed files with 259 additions and 154 deletions

No files matched your search

-32
View File
@@ -1,35 +1,3 @@
# v1.21.0
## Features
- Add support for minutes and hours in `--time-unit`, as well as short and plural aliases such as `ms`, `seconds`, and `min`, see #960 (@sharkdp)
- Expose `$HYPERFINE_ITERATION` to `--prepare` and `--conclude` commands, see #781 and #807 (@willcl-ark)
- Show elapsed time during the initial benchmark run, see #416 and #581 (@devonhollowood)
- Add colors to `--help` output, see #841 (@starsep)
## Changes
- Format times in CSV exports with six decimal places, see #966 and #972 (@sharkdp)
- Update dependencies and raise the minimum supported Rust version to 1.97, see #934 (@sharkdp)
## Bugfixes
- Reject zero values for `--runs`, `--min-runs`, and `--max-runs` instead of allowing invalid run counts, see #923 (@VXNCXNX, @sharkdp)
- Reject negative parameter-scan steps before expanding ranges, avoiding hangs and excessive memory use, see #951 (@Likio3000)
- Preserve existing export files when command options are invalid, see #950 (@Likio3000)
- Truncate export files when rewriting results to avoid leaving trailing bytes, see #970 (@sharkdp)
- Preserve backticks in command names in Markdown exports, see #947 (@Likio3000)
- Handle broken output pipes gracefully instead of panicking, see #932 (@Mathjk)
- Collect peak memory usage separately for each command on Unix, so commands no longer inherit the peak memory usage of earlier commands, see #965 (@sharkdp)
- Preserve 100-nanosecond precision in Windows CPU times, see #964 (@sharkdp)
- Python scripts: Correct the interpretation of Welch's t-test results, see #943 (@sharkdp)
## Other
- Build binaries for Windows ARM64 and Linux ARM64 musl, see #922 and #924 (@meop)
- Refactor measurement, statistics, and formatting code to use typed quantities, see #954, #958, #961, #967, #969, #971, and #976 (@sharkdp)
- Improve documentation and examples, including comparisons across Git branches, iteration variables, reference commands, and selective failure handling, see #899, #900, #929, and #940 (@xfocus3, @ded-furby, @Likio3000, @sharkdp)
# v1.20.0 # v1.20.0
## Features ## Features
+2 -2
View File
@@ -13,5 +13,5 @@ authors:
repository-code: 'https://github.com/sharkdp/hyperfine' repository-code: 'https://github.com/sharkdp/hyperfine'
abstract: A command-line benchmarking tool. abstract: A command-line benchmarking tool.
license: MIT license: MIT
version: 1.21.0 version: 1.20.0
date-released: '2026-10-05' date-released: '2025-11-18'
Generated
+1 -1
View File
@@ -371,7 +371,7 @@ checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]] [[package]]
name = "hyperfine" name = "hyperfine"
version = "1.21.0" version = "1.20.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"approx", "approx",
+1 -1
View File
@@ -7,7 +7,7 @@ license = "MIT OR Apache-2.0"
name = "hyperfine" name = "hyperfine"
readme = "README.md" readme = "README.md"
repository = "https://github.com/sharkdp/hyperfine" repository = "https://github.com/sharkdp/hyperfine"
version = "1.21.0" version = "1.20.0"
edition = "2018" edition = "2018"
build = "build.rs" build = "build.rs"
rust-version = "1.97.0" rust-version = "1.97.0"
+2 -2
View File
@@ -188,8 +188,8 @@ apt install hyperfine
Alternatively, for the latest version, you can download the appropriate `.deb` package from the [Release page](https://github.com/sharkdp/hyperfine/releases) and install it via `dpkg`: Alternatively, for the latest version, you can download the appropriate `.deb` package from the [Release page](https://github.com/sharkdp/hyperfine/releases) and install it via `dpkg`:
``` ```
wget https://github.com/sharkdp/hyperfine/releases/download/v1.21.0/hyperfine_1.21.0_amd64.deb wget https://github.com/sharkdp/hyperfine/releases/download/v1.20.0/hyperfine_1.20.0_amd64.deb
sudo dpkg -i hyperfine_1.21.0_amd64.deb sudo dpkg -i hyperfine_1.20.0_amd64.deb
``` ```
### On Fedora ### On Fedora
+2
View File
@@ -118,6 +118,8 @@ not every time as would happen with the \fB\-\-prepare\fR option.
.IP .IP
Benchmark \fICMD\fP as the reference for the relative comparison of results. Benchmark \fICMD\fP as the reference for the relative comparison of results.
If this option is not specified, the fastest command is used as the reference. If this option is not specified, the fastest command is used as the reference.
In the command-sorted comparison and exported markup tables, values below 1
indicate commands faster than the reference.
.HP .HP
\fB\-\-reference\-name\fR \fINAME\fP \fB\-\-reference\-name\fR \fINAME\fP
.IP .IP
+7 -28
View File
@@ -6,7 +6,6 @@ pub mod scheduler;
use std::cmp; use std::cmp;
use std::io::{self, Write}; use std::io::{self, Write};
use std::time::Instant;
use crate::benchmark::executor::BenchmarkIteration; use crate::benchmark::executor::BenchmarkIteration;
use crate::command::Command; use crate::command::Command;
@@ -15,9 +14,7 @@ use crate::options::{
}; };
use crate::outlier_detection::OUTLIER_THRESHOLD; use crate::outlier_detection::OUTLIER_THRESHOLD;
use crate::output::console_writeln; use crate::output::console_writeln;
use crate::output::progress_bar::{ use crate::output::progress_bar::get_progress_bar;
finish_initial_measurement, get_progress_bar, start_initial_measurement,
};
use crate::output::warnings::{OutlierWarningOptions, Warnings}; use crate::output::warnings::{OutlierWarningOptions, Warnings};
use crate::parameter::ParameterNameAndValue; use crate::parameter::ParameterNameAndValue;
use crate::quantity::{const_time_from_seconds, ratio, FormatQuantity, Time, Zero}; use crate::quantity::{const_time_from_seconds, ratio, FormatQuantity, Time, Zero};
@@ -247,11 +244,7 @@ impl<'a> Benchmark<'a> {
let progress_bar = if self.options.output_style != OutputStyleOption::Disabled { let progress_bar = if self.options.output_style != OutputStyleOption::Disabled {
Some(get_progress_bar( Some(get_progress_bar(
self.options.run_bounds.min, self.options.run_bounds.min,
if preparation_command.is_some() { "Initial time measurement",
"Running preparation command"
} else {
"Initial run"
},
self.options.output_style, self.options.output_style,
)) ))
} else { } else {
@@ -265,9 +258,6 @@ impl<'a> Benchmark<'a> {
}); });
// Initial timing run // Initial timing run
if let Some(bar) = progress_bar.as_ref() {
start_initial_measurement(bar, Instant::now());
}
let res = self.executor.run_command_and_measure( let res = self.executor.run_command_and_measure(
self.command, self.command,
benchmark_iteration, benchmark_iteration,
@@ -276,18 +266,6 @@ impl<'a> Benchmark<'a> {
)?; )?;
let success = res.exit_status.success(); let success = res.exit_status.success();
if let Some(bar) = progress_bar.as_ref() {
let time_unit = self
.options
.time_unit
.unwrap_or(res.time_wall_clock.suitable_unit());
let estimate = res.time_wall_clock.format(time_unit);
finish_initial_measurement(
bar,
format!("Current estimate: {}", estimate.to_string().green()),
);
}
let conclusion_result = run_conclusion_command(benchmark_iteration)?; let conclusion_result = run_conclusion_command(benchmark_iteration)?;
let conclusion_overhead = conclusion_result.map_or(Time::zero(), |res| { let conclusion_overhead = conclusion_result.map_or(Time::zero(), |res| {
res.time_wall_clock + self.executor.time_overhead() res.time_wall_clock + self.executor.time_overhead()
@@ -321,13 +299,16 @@ impl<'a> Benchmark<'a> {
// Re-configure the progress bar // Re-configure the progress bar
if let Some(bar) = progress_bar.as_ref() { if let Some(bar) = progress_bar.as_ref() {
bar.set_length(count); bar.set_length(count)
bar.inc(1); }
if let Some(bar) = progress_bar.as_ref() {
bar.inc(1)
} }
// Gather statistics (perform the actual benchmark) // Gather statistics (perform the actual benchmark)
for i in 0..count_remaining { for i in 0..count_remaining {
let benchmark_iteration = BenchmarkIteration::Benchmark(i + 1); let benchmark_iteration = BenchmarkIteration::Benchmark(i + 1);
run_preparation_command(benchmark_iteration)?;
let msg = { let msg = {
let t_wall_clock_mean = measurements.time_wall_clock_mean(); let t_wall_clock_mean = measurements.time_wall_clock_mean();
@@ -343,8 +324,6 @@ impl<'a> Benchmark<'a> {
bar.set_message(msg.to_owned()) bar.set_message(msg.to_owned())
} }
run_preparation_command(benchmark_iteration)?;
let res = self.executor.run_command_and_measure( let res = self.executor.run_command_and_measure(
self.command, self.command,
benchmark_iteration, benchmark_iteration,
+97 -30
View File
@@ -3,12 +3,13 @@ use std::cmp::Ordering;
use super::benchmark_result::BenchmarkResult; use super::benchmark_result::BenchmarkResult;
use crate::{ use crate::{
options::SortOrder, options::SortOrder,
quantity::{self, Ratio, Time, Zero}, quantity::{self, Time, Zero},
}; };
#[derive(Debug)] #[derive(Debug)]
pub struct BenchmarkResultWithRelativeSpeed<'a> { pub struct BenchmarkResultWithRelativeSpeed<'a> {
pub result: &'a BenchmarkResult, pub result: &'a BenchmarkResult,
/// Runtime divided by the reference runtime; values below one are faster.
pub relative_speed: f64, pub relative_speed: f64,
pub relative_speed_stddev: Option<f64>, pub relative_speed_stddev: Option<f64>,
pub is_reference: bool, pub is_reference: bool,
@@ -40,7 +41,8 @@ fn compute_relative_speeds<'a>(
let is_reference = result == reference; let is_reference = result == reference;
let relative_ordering = compare_mean_time(result, reference); let relative_ordering = compare_mean_time(result, reference);
if result.mean_wall_clock_time() == Time::zero() { let reference_mean = reference.mean_wall_clock_time();
if reference_mean == Time::zero() {
return BenchmarkResultWithRelativeSpeed { return BenchmarkResultWithRelativeSpeed {
result, result,
relative_speed: if is_reference { 1.0 } else { f64::INFINITY }, relative_speed: if is_reference { 1.0 } else { f64::INFINITY },
@@ -50,13 +52,7 @@ fn compute_relative_speeds<'a>(
}; };
} }
let ratio = match relative_ordering { let ratio = result.mean_wall_clock_time() / reference_mean;
Ordering::Less => reference.mean_wall_clock_time() / result.mean_wall_clock_time(),
Ordering::Equal => Ratio::new::<quantity::ratio>(1.0),
Ordering::Greater => {
result.mean_wall_clock_time() / reference.mean_wall_clock_time()
}
};
// https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas // https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas
// Covariance assumed to be 0, i.e. variables are assumed to be independent // Covariance assumed to be 0, i.e. variables are assumed to be independent
@@ -64,13 +60,11 @@ fn compute_relative_speeds<'a>(
result.measurements.stddev(), result.measurements.stddev(),
reference.measurements.stddev(), reference.measurements.stddev(),
) { ) {
(Some(result_stddev), Some(fastest_stddev)) => Some( (Some(result_stddev), Some(reference_stddev)) => Some(
ratio ((result_stddev / reference_mean).powi(uom::typenum::P2::new())
* ((result_stddev / result.mean_wall_clock_time()) + (ratio * (reference_stddev / reference_mean))
.powi(uom::typenum::P2::new()) .powi(uom::typenum::P2::new()))
+ (fastest_stddev / reference.mean_wall_clock_time()) .sqrt(),
.powi(uom::typenum::P2::new()))
.sqrt(),
), ),
_ => None, _ => None,
}; };
@@ -122,18 +116,25 @@ pub fn compute_with_check(
Some(compute_relative_speeds(results, fastest, sort_order)) Some(compute_relative_speeds(results, fastest, sort_order))
} }
/// Same as compute_with_check, potentially resulting in relative speeds of infinity /// Compute ratios relative to the given reference, or the fastest result if omitted.
pub fn compute( /// A zero reference runtime can produce infinite ratios.
results: &[BenchmarkResult], pub fn compute<'a>(
results: &'a [BenchmarkResult],
sort_order: SortOrder, sort_order: SortOrder,
) -> Vec<BenchmarkResultWithRelativeSpeed<'_>> { reference: Option<&'a BenchmarkResult>,
let fastest = fastest_of(results); ) -> Vec<BenchmarkResultWithRelativeSpeed<'a>> {
let reference = reference.unwrap_or_else(|| fastest_of(results));
compute_relative_speeds(results, fastest, sort_order) compute_relative_speeds(results, reference, sort_order)
} }
#[cfg(test)] #[cfg(test)]
fn create_result(name: &str, mean: f64) -> BenchmarkResult { fn create_result(name: &str, mean: f64) -> BenchmarkResult {
create_result_from_times(name, &[mean])
}
#[cfg(test)]
fn create_result_from_times(name: &str, times: &[f64]) -> BenchmarkResult {
use std::collections::BTreeMap; use std::collections::BTreeMap;
use crate::benchmark::measurement::{Measurement, Measurements}; use crate::benchmark::measurement::{Measurement, Measurements};
@@ -143,11 +144,14 @@ fn create_result(name: &str, mean: f64) -> BenchmarkResult {
command: name.into(), command: name.into(),
command_with_unused_parameters: name.into(), command_with_unused_parameters: name.into(),
measurements: Measurements { measurements: Measurements {
measurements: vec![Measurement { measurements: times
time_wall_clock: Time::new::<second>(mean), .iter()
time_user: Time::new::<second>(mean), .map(|&time| Measurement {
..Default::default() time_wall_clock: Time::new::<second>(time),
}], time_user: Time::new::<second>(time),
..Default::default()
})
.collect(),
}, },
parameters: BTreeMap::new(), parameters: BTreeMap::new(),
} }
@@ -174,13 +178,20 @@ fn test_compute_relative_speed() {
fn test_compute_relative_speed_with_reference() { fn test_compute_relative_speed_with_reference() {
use approx::assert_relative_eq; use approx::assert_relative_eq;
let results = vec![create_result("cmd2", 2.0), create_result("cmd3", 5.0)]; let results = vec![
let reference = create_result("cmd2", 4.0); create_result_from_times("cmd2", &[1.0, 2.0, 3.0]),
create_result_from_times("cmd3", &[4.0, 5.0, 6.0]),
];
let reference = create_result_from_times("reference", &[3.0, 4.0, 5.0]);
let annotated_results = let annotated_results =
compute_with_check_from_reference(&results, &reference, SortOrder::Command).unwrap(); compute_with_check_from_reference(&results, &reference, SortOrder::Command).unwrap();
assert_relative_eq!(2.0, annotated_results[0].relative_speed); assert_relative_eq!(0.5, annotated_results[0].relative_speed);
assert_relative_eq!(
0.2795084971874737,
annotated_results[0].relative_speed_stddev.unwrap()
);
assert_relative_eq!(1.25, annotated_results[1].relative_speed); assert_relative_eq!(1.25, annotated_results[1].relative_speed);
} }
@@ -192,3 +203,59 @@ fn test_compute_relative_speed_for_zero_times() {
assert!(annotated_results.is_none()); assert!(annotated_results.is_none());
} }
#[test]
fn test_reference_ratios_do_not_depend_on_sort_order() {
use approx::assert_relative_eq;
let results = vec![
create_result("reference", 2.0),
create_result("slower", 3.0),
create_result("faster", 1.0),
create_result("equal", 2.0),
];
for sort_order in [SortOrder::Command, SortOrder::MeanTime] {
let entries = compute(&results, sort_order, Some(&results[0]));
for entry in entries {
assert_relative_eq!(
entry
.result
.mean_wall_clock_time()
.get::<quantity::second>()
/ 2.0,
entry.relative_speed
);
assert_eq!(entry.is_reference, entry.result.command == "reference");
}
}
}
#[test]
fn test_reference_ratios_without_stddev() {
let results = vec![
create_result("reference", 2.0),
create_result("faster", 1.0),
];
let entries = compute(&results, SortOrder::Command, Some(&results[0]));
assert_eq!(entries[1].relative_speed, 0.5);
assert_eq!(entries[1].relative_speed_stddev, None);
}
#[test]
fn test_reference_ratios_with_zero_times() {
let results = vec![
create_result_from_times("reference", &[1.0, 2.0, 3.0]),
create_result_from_times("zero", &[0.0, 0.0, 0.0]),
];
let entries = compute(&results, SortOrder::Command, Some(&results[0]));
assert_eq!(entries[1].relative_speed, 0.0);
assert_eq!(entries[1].relative_speed_stddev, Some(0.0));
let entries = compute(&results, SortOrder::Command, Some(&results[1]));
assert_eq!(entries[0].relative_speed, f64::INFINITY);
assert_eq!(entries[0].relative_speed_stddev, None);
assert_eq!(entries[1].relative_speed, 1.0);
assert!(compute_with_check_from_reference(&results, &results[0], SortOrder::Command).is_none());
}
+26 -18
View File
@@ -96,28 +96,36 @@ impl<'a> Scheduler<'a> {
)?; )?;
for item in others { for item in others {
let stddev = if let Some(stddev) = item.relative_speed_stddev { // The prose summary expresses both directions as factors above one.
let (relative_speed, relative_speed_stddev, prefix, suffix) =
match item.relative_ordering {
Ordering::Less => (
format!("{:8.2}", 1.0 / item.relative_speed),
item.relative_speed_stddev
.map(|stddev| stddev / item.relative_speed.powi(2)),
"",
" times slower than",
),
Ordering::Greater => (
format!("{:8.2}", item.relative_speed),
item.relative_speed_stddev,
"",
" times faster than",
),
Ordering::Equal => (
format!("{:.2}", item.relative_speed),
item.relative_speed_stddev,
" As fast (",
") as",
),
};
let stddev = if let Some(stddev) = relative_speed_stddev {
format!(" ± {}", format!("{:.2}", stddev).green()) format!(" ± {}", format!("{:.2}", stddev).green())
} else { } else {
"".into() "".into()
}; };
let comparator = match item.relative_ordering { let comparator =
Ordering::Less => format!( format!("{prefix}{}{stddev}{suffix}", relative_speed.bold().green());
"{}{} times slower than",
format!("{:8.2}", item.relative_speed).bold().green(),
stddev
),
Ordering::Greater => format!(
"{}{} times faster than",
format!("{:8.2}", item.relative_speed).bold().green(),
stddev
),
Ordering::Equal => format!(
" As fast ({}{}) as",
format!("{:.2}", item.relative_speed).bold().green(),
stddev
),
};
console_writeln!( console_writeln!(
stdout, stdout,
"{} {}", "{} {}",
+3 -1
View File
@@ -106,7 +106,9 @@ fn build_command() -> Command {
.value_name("CMD") .value_name("CMD")
.help( .help(
"The reference command for the relative comparison of results. \ "The reference command for the relative comparison of results. \
If this is unset, results are compared with the fastest command as reference." If this is unset, results are compared with the fastest command as reference. \
In the command-sorted comparison and exported markup tables, values below 1 \
indicate commands faster than the reference."
) )
) )
.arg( .arg(
+2 -1
View File
@@ -18,6 +18,7 @@ impl Exporter for CsvExporter {
results: &[BenchmarkResult], results: &[BenchmarkResult],
_unit: Option<TimeUnit>, _unit: Option<TimeUnit>,
_sort_order: SortOrder, _sort_order: SortOrder,
_reference: Option<&BenchmarkResult>,
) -> Result<Vec<u8>> { ) -> Result<Vec<u8>> {
const CSV_UNIT: TimeUnit = TimeUnit::Second; const CSV_UNIT: TimeUnit = TimeUnit::Second;
const CSV_PRECISION: usize = 6; const CSV_PRECISION: usize = 6;
@@ -172,7 +173,7 @@ fn test_csv() {
let actual = String::from_utf8( let actual = String::from_utf8(
exporter exporter
.serialize(&results, Some(TimeUnit::Second), SortOrder::Command) .serialize(&results, Some(TimeUnit::Second), SortOrder::Command, None)
.unwrap(), .unwrap(),
) )
.unwrap(); .unwrap();
+1
View File
@@ -22,6 +22,7 @@ impl Exporter for JsonExporter {
results: &[BenchmarkResult], results: &[BenchmarkResult],
_unit: Option<TimeUnit>, _unit: Option<TimeUnit>,
_sort_order: SortOrder, _sort_order: SortOrder,
_reference: Option<&BenchmarkResult>,
) -> Result<Vec<u8>> { ) -> Result<Vec<u8>> {
let mut output = to_vec_pretty(&HyperfineSummary { results }); let mut output = to_vec_pretty(&HyperfineSummary { results });
if let Ok(ref mut content) = output { if let Ok(ref mut content) = output {
+2 -1
View File
@@ -114,9 +114,10 @@ impl<T: MarkupExporter> Exporter for T {
results: &[BenchmarkResult], results: &[BenchmarkResult],
unit: Option<TimeUnit>, unit: Option<TimeUnit>,
sort_order: SortOrder, sort_order: SortOrder,
reference: Option<&BenchmarkResult>,
) -> Result<Vec<u8>> { ) -> Result<Vec<u8>> {
let unit = unit.unwrap_or_else(|| determine_unit_from_results(results)); let unit = unit.unwrap_or_else(|| determine_unit_from_results(results));
let entries = relative_speed::compute(results, sort_order); let entries = relative_speed::compute(results, sort_order, reference);
let table = self.table_results(&entries, unit); let table = self.table_results(&entries, unit);
Ok(table.as_bytes().to_vec()) Ok(table.as_bytes().to_vec())
+10 -1
View File
@@ -51,6 +51,7 @@ trait Exporter {
results: &[BenchmarkResult], results: &[BenchmarkResult],
unit: Option<TimeUnit>, unit: Option<TimeUnit>,
sort_order: SortOrder, sort_order: SortOrder,
reference: Option<&BenchmarkResult>,
) -> Result<Vec<u8>>; ) -> Result<Vec<u8>>;
} }
@@ -69,6 +70,7 @@ pub struct ExportManager {
exporters: Vec<ExporterWithTarget>, exporters: Vec<ExporterWithTarget>,
time_unit: Option<TimeUnit>, time_unit: Option<TimeUnit>,
sort_order: SortOrder, sort_order: SortOrder,
has_reference: bool,
} }
impl ExportManager { impl ExportManager {
@@ -83,6 +85,7 @@ impl ExportManager {
exporters: vec![], exporters: vec![],
time_unit, time_unit,
sort_order, sort_order,
has_reference: matches.contains_id("reference"),
}; };
{ {
let mut add_exporter = |flag, exporttype| -> Result<()> { let mut add_exporter = |flag, exporttype| -> Result<()> {
@@ -131,10 +134,16 @@ impl ExportManager {
/// if a benchmark fails). In the latter case, we only print to stdout targets (in /// if a benchmark fails). In the latter case, we only print to stdout targets (in
/// order not to clutter the output of hyperfine with intermediate results). /// order not to clutter the output of hyperfine with intermediate results).
pub fn write_results(&self, results: &[BenchmarkResult], intermediate: bool) -> Result<()> { pub fn write_results(&self, results: &[BenchmarkResult], intermediate: bool) -> Result<()> {
// The scheduler benchmarks an explicit reference before the other commands.
let reference = if self.has_reference {
results.first()
} else {
None
};
for e in &self.exporters { for e in &self.exporters {
let content = || { let content = || {
e.exporter e.exporter
.serialize(results, self.time_unit, self.sort_order) .serialize(results, self.time_unit, self.sort_order, reference)
}; };
match e.target { match e.target {
+1 -1
View File
@@ -14,7 +14,7 @@ fn get_output<E: Exporter + Default>(
sort_order: SortOrder, sort_order: SortOrder,
) -> String { ) -> String {
let exporter = E::default(); let exporter = E::default();
String::from_utf8(exporter.serialize(results, unit, sort_order).unwrap()).unwrap() String::from_utf8(exporter.serialize(results, unit, sort_order, None).unwrap()).unwrap()
} }
/// Ensure the makrup output includes the table header and the multiple /// Ensure the makrup output includes the table header and the multiple
+3 -35
View File
@@ -1,6 +1,5 @@
use indicatif::{FormattedDuration, ProgressBar, ProgressState, ProgressStyle}; use indicatif::{ProgressBar, ProgressStyle};
use std::fmt; use std::time::Duration;
use std::time::{Duration, Instant};
use crate::options::OutputStyleOption; use crate::options::OutputStyleOption;
@@ -10,44 +9,13 @@ const TICK_SETTINGS: (&str, u64) = ("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ ", 80);
#[cfg(windows)] #[cfg(windows)]
const TICK_SETTINGS: (&str, u64) = (r"+-x| ", 200); const TICK_SETTINGS: (&str, u64) = (r"+-x| ", 200);
// Keep the message area 30 columns wide across preparation, the initial run,
// and estimates so that switching between them does not move the bar.
const DEFAULT_TEMPLATE: &str = " {spinner} {msg:<30} {wide_bar} ETA {eta_precise} ";
const INITIAL_TEMPLATE: &str =
" {spinner} Initial run: {initial_elapsed:<17} {wide_bar} ETA {eta_precise} ";
/// Show the time elapsed since the initial benchmark command started.
pub fn start_initial_measurement(bar: &ProgressBar, started: Instant) {
let style = bar
.style()
.template(INITIAL_TEMPLATE)
.expect("no template error")
.with_key(
"initial_elapsed",
move |_: &ProgressState, w: &mut dyn fmt::Write| {
write!(w, "{}", FormattedDuration(started.elapsed())).unwrap();
},
);
bar.set_style(style);
}
/// Stop showing the initial timer and display the next phase's message.
pub fn finish_initial_measurement(bar: &ProgressBar, message: String) {
bar.set_message(message);
bar.set_style(
bar.style()
.template(DEFAULT_TEMPLATE)
.expect("no template error"),
);
}
/// Return a pre-configured progress bar /// Return a pre-configured progress bar
pub fn get_progress_bar(length: u64, msg: &str, option: OutputStyleOption) -> ProgressBar { pub fn get_progress_bar(length: u64, msg: &str, option: OutputStyleOption) -> ProgressBar {
let progressbar_style = match option { let progressbar_style = match option {
OutputStyleOption::Basic | OutputStyleOption::Color => ProgressStyle::default_bar(), OutputStyleOption::Basic | OutputStyleOption::Color => ProgressStyle::default_bar(),
_ => ProgressStyle::default_spinner() _ => ProgressStyle::default_spinner()
.tick_chars(TICK_SETTINGS.0) .tick_chars(TICK_SETTINGS.0)
.template(DEFAULT_TEMPLATE) .template(" {spinner} {msg:<30} {wide_bar} ETA {eta_precise} ")
.expect("no template error"), .expect("no template error"),
}; };
+99
View File
@@ -705,6 +705,105 @@ fn shows_benchmark_comparison_relative_to_reference() {
"); ");
} }
#[test]
fn command_sorted_comparison_relative_to_reference() {
let _settings = snapshot_settings().bind_to_scope();
assert_cmd_snapshot!(hyperfine_debug()
.args([
"--style=basic",
"--sort=command",
"--reference=sleep 2",
"--reference-name=baseline",
"sleep 1",
"sleep 3",
"sleep 2",
]), @r"
success: true
exit_code: 0
----- stdout -----
Benchmark 1: baseline
Time (mean ± σ): 2.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]
Range (min … max): 2.000 s … 2.000 s 10 runs
Benchmark 2: sleep 1
Time (mean ± σ): 1.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]
Range (min … max): 1.000 s … 1.000 s 10 runs
Benchmark 3: sleep 3
Time (mean ± σ): 3.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]
Range (min … max): 3.000 s … 3.000 s 10 runs
Benchmark 4: sleep 2
Time (mean ± σ): 2.000 s ± 0.000 s [User: 0.000 s, System: 0.000 s]
Range (min … max): 2.000 s … 2.000 s 10 runs
Relative speed comparison
1.00 baseline
0.50 ± 0.00 sleep 1
1.50 ± 0.00 sleep 3
1.00 ± 0.00 sleep 2
----- stderr -----
");
}
#[test]
fn markdown_export_relative_to_reference() {
let tempdir = tempfile::tempdir().unwrap();
let export_path = tempdir.path().join("results.md");
insta::allow_duplicates! {
for sort_order in ["auto", "command", "mean-time"] {
for to_stdout in [false, true] {
let output = hyperfine_debug()
.args([
"--style=none",
"--time-unit=second",
"--reference=sleep 2",
"--reference-name=baseline",
"sleep 1",
"sleep 3",
])
.arg(format!("--sort={sort_order}"))
.arg("--export-markdown")
.arg(if to_stdout {
std::path::Path::new("-")
} else {
&export_path
})
.assert()
.success()
.get_output()
.stdout
.clone();
let table = if to_stdout {
String::from_utf8(output).unwrap()
} else {
std::fs::read_to_string(&export_path).unwrap()
};
if sort_order == "mean-time" {
insta::assert_snapshot!(table.trim(), @r"
| Command | Mean [s] | Min [s] | Max [s] | Relative |
|:---|---:|---:|---:|---:|
| `sleep 1` | 1.000 ± 0.000 | 1.000 | 1.000 | 0.50 ± 0.00 |
| `baseline` | 2.000 ± 0.000 | 2.000 | 2.000 | 1.00 |
| `sleep 3` | 3.000 ± 0.000 | 3.000 | 3.000 | 1.50 ± 0.00 |
");
} else {
insta::assert_snapshot!(table.trim(), @r"
| Command | Mean [s] | Min [s] | Max [s] | Relative |
|:---|---:|---:|---:|---:|
| `baseline` | 2.000 ± 0.000 | 2.000 | 2.000 | 1.00 |
| `sleep 1` | 1.000 ± 0.000 | 1.000 | 1.000 | 0.50 ± 0.00 |
| `sleep 3` | 3.000 ± 0.000 | 3.000 | 3.000 | 1.50 ± 0.00 |
");
}
}
}
}
}
#[test] #[test]
fn shows_reference_name() { fn shows_reference_name() {
let _settings = snapshot_settings().bind_to_scope(); let _settings = snapshot_settings().bind_to_scope();