From 2b47531b23b262dad5de341b8848b139cd363c68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robin=20B=C3=BCrgi?= Date: Sun, 29 Nov 2026 12:02:36 +0000 Subject: [PATCH 1/2] Add --bytes for human-readable throughput --- .../scripts/record_preview.py | 7 +- README.md | 4 + src/main.rs | 23 ++- src/measurements.rs | 136 +++++++++++++++--- src/speedtest.rs | 30 +++- tests/cli.rs | 55 +++++++ tests/cli_terminal.rs | 33 +++++ 7 files changed, 265 insertions(+), 23 deletions(-) diff --git a/.agents/skills/interactive-cli-pr/scripts/record_preview.py b/.agents/skills/interactive-cli-pr/scripts/record_preview.py index d7f6d89..de18f31 100644 --- a/.agents/skills/interactive-cli-pr/scripts/record_preview.py +++ b/.agents/skills/interactive-cli-pr/scripts/record_preview.py @@ -305,6 +305,7 @@ def main(): "--scenario", choices=("clean", "retry", "partial"), default="clean" ) parser.add_argument("--max-payload-size", choices=tuple(SIZES), default="10m") + parser.add_argument("--bytes", action="store_true", help="Show throughput in MB/s") parser.add_argument( "--max-duration", type=int, @@ -367,8 +368,12 @@ def main(): "--server", url, ] + unit_flag = "" + if args.bytes: + flags.insert(0, "--bytes") + unit_flag = " --bytes" prompt = ( - f"$ cfspeedtest --max-payload-size {args.max_payload_size} --max-duration {args.max_duration} \\\r\n" + f"$ cfspeedtest{unit_flag} --max-payload-size {args.max_payload_size} --max-duration {args.max_duration} \\\r\n" f" --disable-dynamic-max-payload-size --server {url}\r\n" ) code, frames = capture( diff --git a/README.md b/README.md index 8e9bfa7..fb3bc06 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,8 @@ Options: Test upload speed only --generate-completion Generate shell completion script for the specified shell [possible values: bash, elvish, fish, powershell, zsh] + --bytes + Show human-readable throughput in MB/s instead of Mbit/s --server Base URL of a compatible Cloudflare speed-test service [default: https://speed.cloudflare.com] --max-duration @@ -68,6 +70,8 @@ Example with json-pretty output: In human-readable mode, live progress is shown on stderr only when it is a terminal. When both stdout and stderr are terminals, each completed transfer size adds a row to the results table. Redirecting stdout keeps the end-of-run summary instead, without progress redraws. CSV and JSON modes never draw a progress bar. +Use `cfspeedtest --bytes` to show throughput in decimal megabytes per second (`MB/s`) in the live display and summary. For example, `100 Mbit/s` is `12.50 MB/s`. The default is decimal megabits per second (`Mbit/s`). Throughput values in CSV, JSON, and JSON-pretty are always in `Mbit/s`; these formats cannot be combined with `--bytes`. + ### Run limits and failures Runs have a shared 120-second measurement deadline and a 30-second cumulative retry-wait budget by default. Both limits cover the entire run, including metadata, latency, and both transfer directions. Each request is limited to the smaller of 30 seconds and the remaining run time. diff --git a/src/main.rs b/src/main.rs index a69edda..8da2354 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,8 @@ mod diagnostics; +use cfspeedtest::measurements::ThroughputUnit; use cfspeedtest::run::RunConfig; -use cfspeedtest::speedtest::speed_test_with_config; +use cfspeedtest::speedtest::speed_test_with_config_and_unit; use cfspeedtest::stdout; use cfspeedtest::{OutputFormat, SpeedTestCLIOptions}; use clap::error::ErrorKind; @@ -19,6 +20,9 @@ use std::time::Duration; struct CliOptions { #[command(flatten)] options: SpeedTestCLIOptions, + /// Show human-readable throughput in MB/s instead of Mbit/s + #[arg(long)] + bytes: bool, /// Base URL of a compatible Cloudflare speed-test service #[arg(long, default_value = "https://speed.cloudflare.com")] server: reqwest::Url, @@ -74,6 +78,20 @@ fn main() -> ExitCode { env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("off")).init(); let cli = CliOptions::parse(); let options = cli.options; + let human_output = options.output_format == OutputFormat::StdOut; + if cli.bytes && !human_output { + CliOptions::command() + .error( + ErrorKind::ArgumentConflict, + "--bytes is only available with human-readable output (default or -o stdout)", + ) + .exit(); + } + let throughput_unit = if cli.bytes { + ThroughputUnit::Megabytes + } else { + ThroughputUnit::Megabits + }; let local_address = local_address(&options); if let Some(generator) = options.completion { @@ -111,11 +129,10 @@ fn main() -> ExitCode { eprintln!("Failed to install cancellation handler: {error}"); return ExitCode::FAILURE; } - let human_output = options.output_format == OutputFormat::StdOut; if human_output { stdout::write(|stdout| writeln!(stdout, "Starting Cloudflare speed test")); } - let report = speed_test_with_config(client, options, config); + let report = speed_test_with_config_and_unit(client, options, config, throughput_unit); if human_output { // Diagnostics are best-effort and do not change the run's exit status. let _ = diagnostics::write_human(&report, io::stderr().lock()); diff --git a/src/measurements.rs b/src/measurements.rs index 3132c14..7ee205b 100644 --- a/src/measurements.rs +++ b/src/measurements.rs @@ -11,6 +11,36 @@ use std::{ io::{self, Write}, }; +/// Decimal throughput unit used in human-readable output. +#[derive(Clone, Copy, Debug, Default)] +pub enum ThroughputUnit { + /// Megabits per second (Mbit/s). + #[default] + Megabits, + /// Megabytes per second (MB/s). + Megabytes, +} + +impl ThroughputUnit { + pub(crate) fn label(self) -> &'static str { + match self { + Self::Megabits => "Mbit/s", + Self::Megabytes => "MB/s", + } + } + + pub(crate) fn convert(self, mbits_per_second: f64) -> f64 { + match self { + Self::Megabits => mbits_per_second, + Self::Megabytes => mbits_per_second / 8.0, + } + } + + fn display_stats(self, (min, q1, median, q3, max, avg): ThroughputStats) -> [f64; 6] { + [min, q1, median, q3, max, avg].map(|rate| self.convert(rate)) + } +} + #[derive(Serialize)] struct StatMeasurement { test_type: TestType, @@ -112,13 +142,15 @@ pub(crate) mod transfer_columns { /// A running summary for interactive output. Each payload is rendered once. pub(crate) struct TransferTable { verbose: bool, + unit: ThroughputUnit, started: bool, } impl TransferTable { - pub(crate) fn new(verbose: bool) -> Self { + pub(crate) fn new(verbose: bool, unit: ThroughputUnit) -> Self { Self { verbose, + unit, started: false, } } @@ -139,7 +171,10 @@ impl TransferTable { .chars() .map(|c| if c == '|' { '+' } else { '-' }) .collect(); - format!("Speed test results (Mbit/s)\n\n{header}\n{rule}\n") + format!( + "Speed test results ({})\n\n{header}\n{rule}\n", + self.unit.label() + ) } pub(crate) fn print_row(&self, attempts: &PayloadAttemptStats, samples: &[Measurement]) { @@ -147,10 +182,11 @@ impl TransferTable { } fn render_row(&self, attempts: &PayloadAttemptStats, samples: &[Measurement]) -> String { - let stats = calc_stats(samples.iter().map(|sample| sample.mbit).collect()); + let stats = calc_stats(samples.iter().map(|sample| sample.mbit).collect()) + .map(|stats| self.unit.display_stats(stats)); let [avg, min, max] = stats.map_or_else( || ["N/A".to_owned(), "N/A".to_owned(), "N/A".to_owned()], - |(min, _, _, _, max, avg)| [avg, min, max].map(format_table_rate), + |[min, _, _, _, max, avg]| [avg, min, max].map(format_table_rate), ); let label = transfer_columns::payload_label(attempts.test_type, attempts.payload_size); let count = format!("{}/{}", attempts.successes, attempts.target_successes); @@ -163,7 +199,7 @@ impl TransferTable { } output.push('\n'); if self.verbose { - if let Some((min, q1, median, q3, max, _)) = stats { + if let Some([min, q1, median, q3, max, _]) = stats { let plot = boxplot::render_plot(min, q1, median, q3, max); output.push_str(&format!("{plot}\n\n")); } @@ -187,18 +223,21 @@ pub(crate) fn log_measurements( payload_sizes: Vec, verbose: bool, output_format: OutputFormat, + throughput_unit: ThroughputUnit, ) { let measurements = &report.measurements; let payload_attempt_stats = &report.payload_attempt_stats; if output_format == OutputFormat::StdOut { stdout::print_line(format_args!("\nSummary Statistics")); - if verbose { - stdout::print_line(format_args!( - "Type Payload | min/max/avg in Mbit/s | attempts/success/skipped", - )); + let label = throughput_unit.label(); + let counts = if verbose { + " | attempts/success/skipped" } else { - stdout::print_line(format_args!("Type Payload | min/max/avg in Mbit/s")); - } + "" + }; + stdout::print_line(format_args!( + "Type Payload | min/max/avg in {label}{counts}" + )); } let mut stat_measurements: Vec = Vec::new(); let mut test_types = measurements @@ -216,6 +255,7 @@ pub(crate) fn log_measurements( payload_sizes.clone(), verbose, output_format, + throughput_unit, *test_type, )) }); @@ -307,6 +347,7 @@ fn log_measurements_by_test_type( payload_sizes: Vec, verbose: bool, output_format: OutputFormat, + throughput_unit: ThroughputUnit, test_type: TestType, ) -> Vec { let mut stat_measurements: Vec = Vec::new(); @@ -333,9 +374,7 @@ fn log_measurements_by_test_type( let formatted_payload = format_bytes(payload_size); let fmt_test_type = format!("{test_type:?}"); - if !type_measurements.is_empty() { - let (min, q1, median, q3, max, avg) = calc_stats(type_measurements).unwrap(); - + if let Some(stats @ (min, q1, median, q3, max, avg)) = calc_stats(type_measurements) { stat_measurements.push(StatMeasurement { test_type, payload_size, @@ -351,6 +390,7 @@ fn log_measurements_by_test_type( target_successes, }); if output_format == OutputFormat::StdOut { + let [min, q1, median, q3, max, avg] = throughput_unit.display_stats(stats); if verbose { stdout::print_line(format_args!( "{fmt_test_type:<9} {formatted_payload:<7}| min {min:<7.2} max {max:<7.2} avg {avg:<7.2} | {attempts:>3}/{successes:>3}/{skipped:>3}" @@ -402,7 +442,9 @@ fn log_measurements_by_test_type( stat_measurements } -fn calc_stats(mbit_measurements: Vec) -> Option<(f64, f64, f64, f64, f64, f64)> { +type ThroughputStats = (f64, f64, f64, f64, f64, f64); + +fn calc_stats(mbit_measurements: Vec) -> Option { log::debug!("calc_stats for mbit_measurements {mbit_measurements:?}"); let length = mbit_measurements.len(); if length == 0 { @@ -475,7 +517,7 @@ mod tests { #[test] fn interactive_table_aligns_dividers_and_keeps_partial_and_empty_payloads() { - let table = TransferTable::new(false); + let table = TransferTable::new(false, ThroughputUnit::Megabits); let partial = PayloadAttemptStats { test_type: TestType::Download, payload_size: 100_000, @@ -517,6 +559,68 @@ mod tests { ); } + #[test] + fn byte_display_converts_table_statistics_and_boxplot_axis() { + let table = TransferTable::new(true, ThroughputUnit::Megabytes); + let attempts = PayloadAttemptStats { + test_type: TestType::Download, + payload_size: 100_000, + attempts: 2, + successes: 2, + skipped: 0, + target_successes: 2, + }; + let samples = [60.0, 100.0].map(|mbit| Measurement { + test_type: attempts.test_type, + payload_size: attempts.payload_size, + mbit, + }); + assert!(table + .render_header() + .starts_with("Speed test results (MB/s)\n")); + let row = table.render_row(&attempts, &samples); + let mut lines = row.lines(); + assert_eq!( + lines.next().unwrap().split_whitespace().collect::>(), + ["Download", "100", "KB", "|", "10.00", "7.50", "12.50", "|", "2/2", "2", "0"] + ); + let axis = lines.nth(1).unwrap(); + assert_eq!( + axis.split_whitespace().collect::>(), + ["7.50", "10.00", "12.50"] + ); + } + + #[test] + fn machine_statistics_always_use_megabits() { + let sample = Measurement { + test_type: TestType::Download, + payload_size: 100_000, + mbit: 100.0, + }; + for format in [ + OutputFormat::Csv, + OutputFormat::Json, + OutputFormat::JsonPretty, + ] { + let stats = log_measurements_by_test_type( + std::slice::from_ref(&sample), + &[], + vec![sample.payload_size], + false, + format, + ThroughputUnit::Megabytes, + sample.test_type, + ); + assert_eq!(stats.len(), 1); + let stat = &stats[0]; + assert_eq!( + [stat.min, stat.q1, stat.median, stat.q3, stat.max, stat.avg], + [Some(100.0); 6] + ); + } + } + #[test] fn live_bar_brackets_replace_table_dividers() { use transfer_columns::{BAR_OFFSET, BAR_WIDTH, ROW_WIDTH, SAMPLES_WIDTH}; diff --git a/src/speedtest.rs b/src/speedtest.rs index 6a3dee9..be326bc 100644 --- a/src/speedtest.rs +++ b/src/speedtest.rs @@ -2,7 +2,7 @@ use crate::measurements::format_bytes; use crate::measurements::log_measurements; use crate::measurements::Measurement; use crate::measurements::PayloadAttemptStats; -use crate::measurements::{transfer_columns, TransferTable}; +use crate::measurements::{transfer_columns, ThroughputUnit, TransferTable}; use crate::progress::{print_progress, Progress}; use crate::run::{ interruptible_sleep, LatencyReport, LatencyStatus, MeasurementError, RunConfig, RunControl, @@ -43,6 +43,7 @@ const RETRY_MAX_BACKOFF: Duration = Duration::from_secs(3); struct RetryRunOptions { nr_tests: u32, output_format: OutputFormat, + throughput_unit: ThroughputUnit, disable_dynamic_max_payload_size: bool, } @@ -122,6 +123,17 @@ pub fn speed_test_with_config( client: Client, options: SpeedTestCLIOptions, config: RunConfig, +) -> SpeedTestReport { + speed_test_with_config_and_unit(client, options, config, ThroughputUnit::default()) +} + +/// Like [`speed_test_with_config`], with a unit for human-readable throughput. +/// Returned samples and machine-readable output always use Mbit/s. +pub fn speed_test_with_config_and_unit( + client: Client, + options: SpeedTestCLIOptions, + config: RunConfig, + throughput_unit: ThroughputUnit, ) -> SpeedTestReport { let mut control = RunControl::new(config); let base_url = control.config.base_url.trim_end_matches('/').to_string(); @@ -151,13 +163,14 @@ pub fn speed_test_with_config( let retry_options = RetryRunOptions { nr_tests: options.nr_tests, output_format: options.output_format, + throughput_unit, disable_dynamic_max_payload_size: options.disable_dynamic_max_payload_size, }; // Keep the end-of-run summary when output is redirected or logging is enabled. let interactive = Progress::allows_live_output(options.output_format) && io::stdout().is_terminal() && io::stderr().is_terminal(); - let mut table = interactive.then(|| TransferTable::new(options.verbose)); + let mut table = interactive.then(|| TransferTable::new(options.verbose, throughput_unit)); let mut measurements = Vec::new(); let mut payload_attempt_stats = Vec::new(); let cancelled = control.config.cancelled.clone(); @@ -210,6 +223,7 @@ pub fn speed_test_with_config( payload_sizes, options.verbose, options.output_format, + throughput_unit, ); } report @@ -465,6 +479,7 @@ pub fn run_tests_with_retries( RetryRunOptions { nr_tests, output_format, + throughput_unit: ThroughputUnit::default(), disable_dynamic_max_payload_size, }, &mut control, @@ -579,8 +594,11 @@ fn run_tests_with_control( successes += 1; progress.set_position(successes); progress.set_status(|| { + let unit = options.throughput_unit; format!( - "> Last sample: {mbits:.2} Mbit/s in {} ms", + "> Last sample: {:.2} {} in {} ms", + unit.convert(mbits), + unit.label(), duration.as_millis() ) }); @@ -1410,6 +1428,7 @@ mod tests { RetryRunOptions { nr_tests: 1, output_format: OutputFormat::None, + throughput_unit: ThroughputUnit::default(), disable_dynamic_max_payload_size: true, }, &base_url, @@ -1464,6 +1483,7 @@ mod tests { RetryRunOptions { nr_tests: 6, output_format: OutputFormat::None, + throughput_unit: ThroughputUnit::default(), disable_dynamic_max_payload_size: true, }, &base_url, @@ -1535,6 +1555,7 @@ mod tests { RetryRunOptions { nr_tests: 2, output_format: OutputFormat::None, + throughput_unit: ThroughputUnit::default(), disable_dynamic_max_payload_size: true, }, &base_url, @@ -1585,6 +1606,7 @@ mod tests { RetryRunOptions { nr_tests: 2, output_format: OutputFormat::None, + throughput_unit: ThroughputUnit::default(), disable_dynamic_max_payload_size: true, }, &base_url, @@ -1622,6 +1644,7 @@ mod tests { RetryRunOptions { nr_tests: 2, output_format: OutputFormat::None, + throughput_unit: ThroughputUnit::default(), disable_dynamic_max_payload_size: true, }, &base_url, @@ -1670,6 +1693,7 @@ mod tests { let options = RetryRunOptions { nr_tests: 1, output_format: OutputFormat::None, + throughput_unit: ThroughputUnit::default(), disable_dynamic_max_payload_size: true, }; let delays = std::cell::RefCell::new(Vec::new()); diff --git a/tests/cli.rs b/tests/cli.rs index b63314a..af998bb 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -110,6 +110,61 @@ fn redirected_human_output_has_no_progress() { } } +#[test] +fn redirected_bytes_output_labels_throughput_without_redraws() { + let server = Server::new(Response::normal); + let output = server + .command(&[ + "--bytes", + "-o", + "stdout", + "--verbose", + "--nr-latency-tests", + "1", + ]) + .env("TERM", "xterm") + .env("RUST_LOG", "off") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(0), "{stderr}"); + assert!( + stdout.contains("min/max/avg in MB/s | attempts/success/skipped"), + "{stdout}" + ); + assert!(stdout.contains("Download 100KB"), "{stdout}"); + assert!( + stdout.contains("Avg GET request latency") && stdout.contains("ms"), + "{stdout}" + ); + assert!(!stdout.contains("Mbit/s"), "{stdout}"); + assert!(!stdout.contains("Last sample:"), "{stdout}"); + assert!(!stdout.contains(['\r', '\x1b']), "{stdout:?}"); + assert!(stderr.is_empty(), "{stderr}"); +} + +#[test] +fn bytes_is_rejected_with_machine_readable_output_before_any_request() { + let requests = Arc::new(AtomicUsize::new(0)); + let observed = requests.clone(); + let server = Server::new(move |path| { + observed.fetch_add(1, Ordering::SeqCst); + Response::normal(path) + }); + for format in ["csv", "json", "json-pretty"] { + let output = run_piped(&server, &["--bytes", "-o", format]); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{format}: {stderr}"); + assert!( + stderr.contains("--bytes is only available with human-readable output"), + "{format}: {stderr}" + ); + assert!(output.stdout.is_empty(), "{format}"); + } + assert_eq!(requests.load(Ordering::SeqCst), 0); +} + #[test] fn human_output_explains_partial_results() { let downloads = AtomicUsize::new(0); diff --git a/tests/cli_terminal.rs b/tests/cli_terminal.rs index c85d7d2..43da71c 100644 --- a/tests/cli_terminal.rs +++ b/tests/cli_terminal.rs @@ -156,6 +156,10 @@ fn shows_retry_during_backoff_without_counting_it_as_a_sample() { ); let transcript = text(&chunks); + assert!( + transcript.contains("Speed test results (Mbit/s)"), + "{transcript:?}" + ); let completed_row = "Download 100 KB |"; assert_eq!( transcript.matches(completed_row).count(), @@ -229,6 +233,35 @@ fn ctrl_c_replaces_the_live_row_with_one_partial_result() { assert!(screen.contains("Run stopped: Cancelled"), "{screen}"); } +#[test] +fn shows_bytes_in_live_status_and_results_table() { + let server = Server::new(|path| { + let mut response = Response::normal(path); + if path == "/__down?bytes=100000" { + // Allow successive progress draws to show the preceding sample. + response.delay = Duration::from_millis(150); + } + response + }); + let command = server.command(&["-o", "stdout", "-n", "3", "--bytes"]); + let transcript = text(&terminal_output(command, None)); + assert!( + transcript.contains("Speed test results (MB/s)"), + "{transcript:?}" + ); + assert!( + transcript + .lines() + .any(|line| line.contains("Last sample:") && line.contains("MB/s in")), + "{transcript:?}" + ); + assert!( + transcript.contains("Download 100 KB |"), + "{transcript:?}" + ); + assert!(!transcript.contains("Mbit/s"), "{transcript:?}"); +} + #[test] fn keeps_dependency_logs_and_disables_terminal_redraws() { // The fixture closes each connection, so reqwest logs during each request. From b9e4ebd7fff4dfd6eb8aacc1800f4897aa1b3fab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robin=20B=C3=BCrgi?= Date: Sun, 29 Nov 2026 12:05:19 +0000 Subject: [PATCH 2/2] Clarify throughput units in the README --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index fb3bc06..0639490 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,9 @@ Example with json-pretty output: In human-readable mode, live progress is shown on stderr only when it is a terminal. When both stdout and stderr are terminals, each completed transfer size adds a row to the results table. Redirecting stdout keeps the end-of-run summary instead, without progress redraws. CSV and JSON modes never draw a progress bar. -Use `cfspeedtest --bytes` to show throughput in decimal megabytes per second (`MB/s`) in the live display and summary. For example, `100 Mbit/s` is `12.50 MB/s`. The default is decimal megabits per second (`Mbit/s`). Throughput values in CSV, JSON, and JSON-pretty are always in `Mbit/s`; these formats cannot be combined with `--bytes`. +By default, cfspeedtest reports throughput in decimal megabits per second (`Mbit/s`). Use `cfspeedtest --bytes` to see decimal megabytes per second (`MB/s`) in the live display and summary. For example, `100 Mbit/s` is `12.50 MB/s`. + +CSV, JSON, and JSON-pretty always report throughput in `Mbit/s` and do not support `--bytes`. ### Run limits and failures