Skip to content
Myr

Support hardware counters (instructions, cache misses, ...) (#983)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Add hardware counters to JSON exports * Clarify Linux hardware counter setup

authored by David Peter · committed by GitHub · parent ab86cb9 · Browse files · 13 files+432 added−34 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+432 added−34 removed

  • other:+432 added−34 removed

13 files+432 added−34 removed

modified:src/benchmark/executor.rs+6 added-1 removed
60 unmodified lines
61 command_failure_action: CmdFailureAction,62 command_input_policy: &CommandInputPolicy,63 command_output_policy: &CommandOutputPolicy,64 command_name: &str,65 collect_hardware_counters: bool,66) -> Result<Measurement> {67 let stdin = command_input_policy.get_stdin()?;68 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;69 command.stdin(stdin).stdout(stdout).stderr(stderr);
6 unmodified lines
76 if let Some(value) = iteration.to_env_var_value() {77 command.env("HYPERFINE_ITERATION", value);78 }7979 let measurement = execute_and_measure(command)80 let measurement = execute_and_measure(command, collect_hardware_counters)81 .with_context(|| format!("Failed to run command '{command_name}'"))?;8283 if !measurement.exit_status.success() {84 use crate::util::exit_code::extract_exit_code;
59 unmodified lines
144 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),145 &self.options.command_input_policy,146 output_policy,147 &command.get_command_line(),148 matches!(iteration, BenchmarkIteration::Benchmark(_)),149 )150 }151152 fn calibrate(&mut self) -> Result<()> {
47 unmodified lines
200 command_failure_action.unwrap_or_else(|| self.options.command_failure_action.clone()),201 &self.options.command_input_policy,202 output_policy,203 &command.get_command_line(),204 false,205 )?;206207 // Subtract shell spawning time208 fn ensure_non_negative(time: Time) -> Time {
71 unmodified lines
280 time_wall_clock: measurements.time_wall_clock_mean(),281 time_user: measurements.time_user_mean(),282 time_system: measurements.time_system_mean(),283 memory_peak_resident: None,284 hardware_counters: Default::default(),285 exit_status: ExitStatus::default(),286 });287288 Ok(())
50 unmodified lines
339 time_wall_clock: Self::extract_time(command.get_command_line()),340 time_user: Time::zero(),341 time_system: Time::zero(),342 memory_peak_resident: Some(Information::zero()),343 hardware_counters: Default::default(),344 exit_status,345 })346 }347
19 unmodified lines
modified:src/benchmark/measurement.rs+44 added
27 unmodified lines
28 None => serializer.serialize_none(),29 }30}3132fn serialize_optional_count<S>(value: &Option<u64>, serializer: S) -> Result<S::Ok, S::Error>33where34 S: serde::Serializer,35{36 #[derive(Serialize)]37 struct Count {38 value: u64,39 }4041 value.map(|value| Count { value }).serialize(serializer)42}4344#[derive(Debug, Clone, Default, Serialize, PartialEq)]45pub struct HardwareCounters {46 #[serde(47 skip_serializing_if = "Option::is_none",48 serialize_with = "serialize_optional_count"49 )]50 pub cpu_cycles: Option<u64>,51 #[serde(52 skip_serializing_if = "Option::is_none",53 serialize_with = "serialize_optional_count"54 )]55 pub instructions: Option<u64>,56 #[serde(57 skip_serializing_if = "Option::is_none",58 serialize_with = "serialize_optional_count"59 )]60 pub cache_references: Option<u64>,61 #[serde(62 skip_serializing_if = "Option::is_none",63 serialize_with = "serialize_optional_count"64 )]65 pub cache_misses: Option<u64>,66 #[serde(67 skip_serializing_if = "Option::is_none",68 serialize_with = "serialize_optional_count"69 )]70 pub branch_misses: Option<u64>,71}7273/// Performance metric measurements and exit code for a single run74#[derive(Debug, Clone, Default, Serialize, PartialEq)]75pub struct Measurement {76 /// Elapsed wall clock time (real time)
14 unmodified lines
91 serialize_with = "serialize_optional_information"92 )]93 pub memory_peak_resident: Option<Information>,9495 #[serde(flatten)]96 pub hardware_counters: HardwareCounters,9798 // The exit status of the process99 #[serde(rename = "exit_code", serialize_with = "serialize_exit_status")]100 pub exit_status: ExitStatus,101}
73 unmodified lines
modified:src/export/csv.rs+6 added
87 unmodified lines
88 time_wall_clock: Time::new::<second>(7.0),89 time_user: Time::new::<second>(7.0),90 time_system: Time::zero(),91 memory_peak_resident: Some(Information::new::<byte>(1024.)),92 hardware_counters: Default::default(),93 exit_status: ExitStatus::default(),94 },95 Measurement {96 time_wall_clock: Time::new::<second>(8.0),97 time_user: Time::new::<second>(8.0),98 time_system: Time::zero(),99 memory_peak_resident: Some(Information::new::<byte>(1024.)),100 hardware_counters: Default::default(),101 exit_status: ExitStatus::default(),102 },103 Measurement {104 time_wall_clock: Time::new::<second>(12.0),105 time_user: Time::new::<second>(12.0),106 time_system: Time::zero(),107 memory_peak_resident: Some(Information::new::<byte>(1024.)),108 hardware_counters: Default::default(),109 exit_status: ExitStatus::default(),110 },111 ]),112 parameters: {
22 unmodified lines
135 time_wall_clock: Time::new::<second>(17.0),136 time_user: Time::new::<second>(17.0),137 time_system: Time::zero(),138 memory_peak_resident: Some(Information::new::<byte>(1024.)),139 hardware_counters: Default::default(),140 exit_status: ExitStatus::default(),141 },142 Measurement {143 time_wall_clock: Time::new::<second>(18.0),144 time_user: Time::new::<second>(18.0),145 time_system: Time::zero(),146 memory_peak_resident: Some(Information::new::<byte>(1024.)),147 hardware_counters: Default::default(),148 exit_status: ExitStatus::default(),149 },150 Measurement {151 time_wall_clock: Time::new::<second>(19.0),152 time_user: Time::new::<second>(19.0),153 time_system: Time::zero(),154 memory_peak_resident: Some(Information::new::<byte>(1024.)),155 hardware_counters: Default::default(),156 exit_status: ExitStatus::default(),157 },158 ]),159 parameters: {
31 unmodified lines
modified:src/export/json.rs+94 added-32 removed
6 unmodified lines
7use crate::benchmark::benchmark_result::BenchmarkResult;8use crate::benchmark::measurement::Measurements;9use crate::options::SortOrder;10use crate::quantity::statistics::{max, mean, median, min, standard_deviation, UnsafeRawValue};11use crate::quantity::{byte, second, QuantityInUnit, Ratio, TimeUnit, Zero};11use crate::quantity::{byte, ratio, second, QuantityInUnit, Ratio, TimeUnit, Zero};1213use anyhow::Result;1415mod metadata;
23 unmodified lines
39 time_user: StatisticalSummary,40 time_system: StatisticalSummary,41 #[serde(skip_serializing_if = "Option::is_none")]42 memory_peak_resident: Option<StatisticalSummary>,43 #[serde(skip_serializing_if = "Option::is_none")]44 cpu_cycles: Option<StatisticalSummary>,45 #[serde(skip_serializing_if = "Option::is_none")]46 instructions: Option<StatisticalSummary>,47 #[serde(skip_serializing_if = "Option::is_none")]48 cache_references: Option<StatisticalSummary>,49 #[serde(skip_serializing_if = "Option::is_none")]50 cache_misses: Option<StatisticalSummary>,51 #[serde(skip_serializing_if = "Option::is_none")]52 branch_misses: Option<StatisticalSummary>,53}5455impl BenchmarkSummary {56 fn from_measurements(measurements: &Measurements) -> Self {57 let values = &measurements.measurements;48 let mut memory_values = values49 .iter()50 .filter_map(|m| m.memory_peak_resident)51 .peekable();58 Self {59 time_wall_clock: StatisticalSummary::from_values(54 values.iter().map(|m| m.time_wall_clock),55 second,56 ),57 time_user: StatisticalSummary::from_values(values.iter().map(|m| m.time_user), second),60 values.iter().map(|m| Some(m.time_wall_clock)),61 Some(second),62 )63 .expect("Benchmarks have at least one measurement"),64 time_user: StatisticalSummary::from_values(65 values.iter().map(|m| Some(m.time_user)),66 Some(second),67 )68 .expect("Benchmarks have at least one measurement"),69 time_system: StatisticalSummary::from_values(59 values.iter().map(|m| m.time_system),60 second,70 values.iter().map(|m| Some(m.time_system)),71 Some(second),72 )73 .expect("Benchmarks have at least one measurement"),74 memory_peak_resident: StatisticalSummary::from_values(75 values76 .iter()77 .filter_map(|m| m.memory_peak_resident)78 .map(Some),79 Some(byte),80 ),62 memory_peak_resident: memory_values63 .peek()64 .is_some()65 .then(|| StatisticalSummary::from_values(memory_values, byte)),81 cpu_cycles: StatisticalSummary::from_values(82 values.iter().map(|m| {83 m.hardware_counters84 .cpu_cycles85 .map(|v| Ratio::new::<ratio>(v as f64))86 }),87 None::<ratio>,88 ),89 instructions: StatisticalSummary::from_values(90 values.iter().map(|m| {91 m.hardware_counters92 .instructions93 .map(|v| Ratio::new::<ratio>(v as f64))94 }),95 None::<ratio>,96 ),97 cache_references: StatisticalSummary::from_values(98 values.iter().map(|m| {99 m.hardware_counters100 .cache_references101 .map(|v| Ratio::new::<ratio>(v as f64))102 }),103 None::<ratio>,104 ),105 cache_misses: StatisticalSummary::from_values(106 values.iter().map(|m| {107 m.hardware_counters108 .cache_misses109 .map(|v| Ratio::new::<ratio>(v as f64))110 }),111 None::<ratio>,112 ),113 branch_misses: StatisticalSummary::from_values(114 values.iter().map(|m| {115 m.hardware_counters116 .branch_misses117 .map(|v| Ratio::new::<ratio>(v as f64))118 }),119 None::<ratio>,120 ),121 }122 }123}124125#[derive(Serialize)]126struct StatisticalSummary {72 unit: &'static str,127 #[serde(skip_serializing_if = "Option::is_none")]128 unit: Option<&'static str>,129 count: usize,130 mean: f64,131 stddev: Option<f64>,132 median: f64,
1 unmodified line
134 max: f64,135}136137impl StatisticalSummary {82 fn from_values<Q, P, U>(values: impl IntoIterator<Item = Q>, _unit: U) -> Self138 fn from_values<Q, P, U>(139 values: impl IntoIterator<Item = Option<Q>>,140 unit: Option<U>,141 ) -> Option<Self>142 where143 Q: Copy144 + PartialOrd145 + Add<Output = Q>
4 unmodified lines
150 + QuantityInUnit<U>,151 P: Into<Q>,152 U: uom::si::Unit,153 {95 let values: Vec<_> = values.into_iter().collect();96 assert!(97 !values.is_empty(),98 "Statistical summaries require at least one measurement"99 );100 Self {101 unit: U::singular(),154 // Only summarize a metric when it is available for every supplied measurement.155 let values: Vec<_> = values.into_iter().collect::<Option<_>>()?;156 if values.is_empty() {157 return None;158 }159 Some(Self {160 unit: unit.map(|_| U::singular()),161 count: values.len(),162 mean: mean(values.iter().copied()).value_in_unit(),163 stddev: (values.len() > 1)164 .then(|| standard_deviation(values.iter().copied()).value_in_unit()),165 median: median(values.iter().copied()).value_in_unit(),166 min: min(values.iter().copied()).value_in_unit(),167 max: max(values.iter().copied()).value_in_unit(),109 }168 })169 }170}171172#[derive(Default)]
34 unmodified lines
207fn test_statistical_summary_unit_conversion() {208 use crate::quantity::{kibibyte, millisecond, Information, Time};209210 let time = StatisticalSummary::from_values(152 [Time::new::<second>(1.0), Time::new::<second>(3.0)],153 millisecond,154 );211 [Time::new::<second>(1.0), Time::new::<second>(3.0)].map(Some),212 Some(millisecond),213 )214 .unwrap();215 let information = StatisticalSummary::from_values(216 [217 Information::new::<byte>(1024.0),218 Information::new::<byte>(3072.0),159 ],160 kibibyte,161 );219 ]220 .map(Some),221 Some(kibibyte),222 )223 .unwrap();224225 for (summary, unit, scale) in [226 (time, "millisecond", 1000.0),227 (information, "kibibyte", 1.0),228 ] {167 assert_eq!(summary.unit, unit);229 assert_eq!(summary.unit, Some(unit));230 assert_eq!(summary.count, 2);231 approx::assert_relative_eq!(summary.mean, 2.0 * scale);232 approx::assert_relative_eq!(summary.median, 2.0 * scale);233 approx::assert_relative_eq!(summary.min, scale);
4 unmodified lines
modified:src/export/tests.rs+24 added
34 unmodified lines
35 time_wall_clock: Time::new::<second>(0.09),36 time_user: Time::new::<second>(0.09),37 time_system: Time::zero(),38 memory_peak_resident: Some(Information::new::<byte>(1024.)),39 hardware_counters: Default::default(),40 exit_status: ExitStatus::default(),41 },42 Measurement {43 time_wall_clock: Time::new::<second>(0.10),44 time_user: Time::new::<second>(0.10),45 time_system: Time::zero(),46 memory_peak_resident: Some(Information::new::<byte>(1024.)),47 hardware_counters: Default::default(),48 exit_status: ExitStatus::default(),49 },50 Measurement {51 time_wall_clock: Time::new::<second>(0.14),52 time_user: Time::new::<second>(0.14),53 time_system: Time::zero(),54 memory_peak_resident: Some(Information::new::<byte>(1024.)),55 hardware_counters: Default::default(),56 exit_status: ExitStatus::default(),57 },58 ]),59 parameters: BTreeMap::new(),
7 unmodified lines
67 time_wall_clock: Time::new::<second>(2.0),68 time_user: Time::new::<second>(2.0),69 time_system: Time::zero(),70 memory_peak_resident: Some(Information::new::<byte>(1024.)),71 hardware_counters: Default::default(),72 exit_status: ExitStatus::default(),73 },74 Measurement {75 time_wall_clock: Time::new::<second>(3.0),76 time_user: Time::new::<second>(3.0),77 time_system: Time::zero(),78 memory_peak_resident: Some(Information::new::<byte>(1024.)),79 hardware_counters: Default::default(),80 exit_status: ExitStatus::default(),81 },82 Measurement {83 time_wall_clock: Time::new::<second>(4.0),84 time_user: Time::new::<second>(4.0),85 time_system: Time::zero(),86 memory_peak_resident: Some(Information::new::<byte>(1024.)),87 hardware_counters: Default::default(),88 exit_status: ExitStatus::default(),89 },90 ]),91 parameters: BTreeMap::new(),
52 unmodified lines
144 time_wall_clock: Time::new::<second>(2.1),145 time_user: Time::new::<second>(2.1),146 time_system: Time::zero(),147 memory_peak_resident: Some(Information::new::<byte>(1024.)),148 hardware_counters: Default::default(),149 exit_status: ExitStatus::default(),150 },151 Measurement {152 time_wall_clock: Time::new::<second>(2.2),153 time_user: Time::new::<second>(2.2),154 time_system: Time::zero(),155 memory_peak_resident: Some(Information::new::<byte>(1024.)),156 hardware_counters: Default::default(),157 exit_status: ExitStatus::default(),158 },159 Measurement {160 time_wall_clock: Time::new::<second>(2.3),161 time_user: Time::new::<second>(2.3),162 time_system: Time::zero(),163 memory_peak_resident: Some(Information::new::<byte>(1024.)),164 hardware_counters: Default::default(),165 exit_status: ExitStatus::default(),166 },167 ]),168 parameters: BTreeMap::new(),
7 unmodified lines
176 time_wall_clock: Time::new::<second>(0.1),177 time_user: Time::new::<second>(0.1),178 time_system: Time::zero(),179 memory_peak_resident: Some(Information::new::<byte>(1024.)),180 hardware_counters: Default::default(),181 exit_status: ExitStatus::default(),182 },183 Measurement {184 time_wall_clock: Time::new::<second>(0.2),185 time_user: Time::new::<second>(0.2),186 time_system: Time::zero(),187 memory_peak_resident: Some(Information::new::<byte>(1024.)),188 hardware_counters: Default::default(),189 exit_status: ExitStatus::default(),190 },191 Measurement {192 time_wall_clock: Time::new::<second>(0.3),193 time_user: Time::new::<second>(0.3),194 time_system: Time::zero(),195 memory_peak_resident: Some(Information::new::<byte>(1024.)),196 hardware_counters: Default::default(),197 exit_status: ExitStatus::default(),198 },199 ]),200 parameters: BTreeMap::new(),
52 unmodified lines
253 time_wall_clock: Time::new::<second>(2.1),254 time_user: Time::new::<second>(2.1),255 time_system: Time::zero(),256 memory_peak_resident: Some(Information::new::<byte>(1024.)),257 hardware_counters: Default::default(),258 exit_status: ExitStatus::default(),259 },260 Measurement {261 time_wall_clock: Time::new::<second>(2.2),262 time_user: Time::new::<second>(2.2),263 time_system: Time::zero(),264 memory_peak_resident: Some(Information::new::<byte>(1024.)),265 hardware_counters: Default::default(),266 exit_status: ExitStatus::default(),267 },268 Measurement {269 time_wall_clock: Time::new::<second>(2.3),270 time_user: Time::new::<second>(2.3),271 time_system: Time::zero(),272 memory_peak_resident: Some(Information::new::<byte>(1024.)),273 hardware_counters: Default::default(),274 exit_status: ExitStatus::default(),275 },276 ]),277 parameters: BTreeMap::new(),
7 unmodified lines
285 time_wall_clock: Time::new::<second>(0.1),286 time_user: Time::new::<second>(0.1),287 time_system: Time::zero(),288 memory_peak_resident: Some(Information::new::<byte>(1024.)),289 hardware_counters: Default::default(),290 exit_status: ExitStatus::default(),291 },292 Measurement {293 time_wall_clock: Time::new::<second>(0.2),294 time_user: Time::new::<second>(0.2),295 time_system: Time::zero(),296 memory_peak_resident: Some(Information::new::<byte>(1024.)),297 hardware_counters: Default::default(),298 exit_status: ExitStatus::default(),299 },300 Measurement {301 time_wall_clock: Time::new::<second>(0.3),302 time_user: Time::new::<second>(0.3),303 time_system: Time::zero(),304 memory_peak_resident: Some(Information::new::<byte>(1024.)),305 hardware_counters: Default::default(),306 exit_status: ExitStatus::default(),307 },308 ]),309 parameters: BTreeMap::new(),
51 unmodified lines
361 time_wall_clock: Time::new::<second>(2.01),362 time_user: Time::new::<second>(2.01),363 time_system: Time::zero(),364 memory_peak_resident: Some(Information::new::<byte>(1024.)),365 hardware_counters: Default::default(),366 exit_status: ExitStatus::default(),367 },368 Measurement {369 time_wall_clock: Time::new::<second>(2.02),370 time_user: Time::new::<second>(2.02),371 time_system: Time::zero(),372 memory_peak_resident: Some(Information::new::<byte>(1024.)),373 hardware_counters: Default::default(),374 exit_status: ExitStatus::default(),375 },376 Measurement {377 time_wall_clock: Time::new::<second>(2.03),378 time_user: Time::new::<second>(2.03),379 time_system: Time::zero(),380 memory_peak_resident: Some(Information::new::<byte>(1024.)),381 hardware_counters: Default::default(),382 exit_status: ExitStatus::default(),383 },384 ]),385 parameters: BTreeMap::new(),
7 unmodified lines
393 time_wall_clock: Time::new::<second>(0.11),394 time_user: Time::new::<second>(0.11),395 time_system: Time::zero(),396 memory_peak_resident: Some(Information::new::<byte>(1024.)),397 hardware_counters: Default::default(),398 exit_status: ExitStatus::default(),399 },400 Measurement {401 time_wall_clock: Time::new::<second>(0.12),402 time_user: Time::new::<second>(0.12),403 time_system: Time::zero(),404 memory_peak_resident: Some(Information::new::<byte>(1024.)),405 hardware_counters: Default::default(),406 exit_status: ExitStatus::default(),407 },408 Measurement {409 time_wall_clock: Time::new::<second>(0.13),410 time_user: Time::new::<second>(0.13),411 time_system: Time::zero(),412 memory_peak_resident: Some(Information::new::<byte>(1024.)),413 hardware_counters: Default::default(),414 exit_status: ExitStatus::default(),415 },416 ]),417 parameters: BTreeMap::new(),
40 unmodified lines
modified:src/quantity/mod.rs+6 added
32 unmodified lines
33 self.get::<U>()34 }35}3637impl<U: uom::si::ratio::Unit + uom::Conversion<f64, T = f64>> QuantityInUnit<U> for Ratio {38 fn value_in_unit(self) -> f64 {39 self.get::<U>()40 }41}4243pub trait FormatQuantity {44 type Unit;4546 fn suitable_unit(&self) -> Self::Unit;
204 unmodified lines
modified:src/quantity/statistics.rs+10 added
89 unmodified lines
90 Information::new::<byte>(value)91 }92}9394impl UnsafeRawValue for Ratio {95 fn unsafe_raw_value(&self) -> f64 {96 self.get::<ratio>()97 }9899 fn unsafe_from_raw_value(value: f64) -> Self {100 Ratio::new::<ratio>(value)101 }102}103104fn standard_deviation_f64(values: &[f64]) -> f64 {105 let mean_value = mean(values.iter().copied());106107 let mut squared_deviations = 0.;
133 unmodified lines
added:src/timer/linux_counters.rs+113 added
1use std::fs::File;2use std::io::Read;34use crate::benchmark::measurement::HardwareCounters;56/// Disabled events on the spawning thread, inherited and enabled by the child's exec.7/// The parent never enables its own events, so its work is not counted.8pub struct CounterGroup {9 events: [Option<File>; 5],10}1112impl CounterGroup {13 #[cfg(all(14 target_pointer_width = "64",15 any(16 target_arch = "aarch64",17 target_arch = "x86_64",18 target_arch = "riscv64",19 target_arch = "powerpc64",20 target_arch = "loongarch64"21 )22 ))]23 pub fn new() -> Self {24 use perf_event_open_sys::{bindings, perf_event_open};25 use std::os::fd::{AsRawFd, FromRawFd};2627 let mut group_leader = -1;28 let events = [29 bindings::PERF_COUNT_HW_CPU_CYCLES,30 bindings::PERF_COUNT_HW_INSTRUCTIONS,31 bindings::PERF_COUNT_HW_CACHE_REFERENCES,32 bindings::PERF_COUNT_HW_CACHE_MISSES,33 bindings::PERF_COUNT_HW_BRANCH_MISSES,34 ]35 .map(|config| {36 let mut attr = bindings::perf_event_attr {37 type_: bindings::PERF_TYPE_HARDWARE,38 size: std::mem::size_of::<bindings::perf_event_attr>() as u32,39 config: u64::from(config),40 ..Default::default()41 };42 // Don't start counting immediately.43 attr.set_disabled(1);44 // Start counting when the child executes the benchmark program.45 attr.set_enable_on_exec(1);46 // New child processes and threads inherit the counters.47 attr.set_inherit(1);48 // Exclude kernel execution.49 attr.set_exclude_kernel(1);50 // Exclude hypervisor execution.51 attr.set_exclude_hv(1);5253 // Attach counters to the calling thread.54 const CURRENT_THREAD: libc::pid_t = 0;55 // Count on whichever CPU the task runs on.56 const ANY_CPU: libc::c_int = -1;5758 // SAFETY: attr is initialized and sized for the kernel API.59 let fd = unsafe {60 perf_event_open(61 &mut attr,62 CURRENT_THREAD,63 ANY_CPU,64 group_leader,65 bindings::PERF_FLAG_FD_CLOEXEC.into(),66 )67 };68 if fd < 0 {69 return None;70 }71 // SAFETY: perf_event_open returned a new, valid descriptor.72 let event = unsafe { File::from_raw_fd(fd) };73 if group_leader == -1 {74 group_leader = event.as_raw_fd();75 }76 Some(event)77 });78 Self { events }79 }8081 #[cfg(not(all(82 target_pointer_width = "64",83 any(84 target_arch = "aarch64",85 target_arch = "x86_64",86 target_arch = "riscv64",87 target_arch = "powerpc64",88 target_arch = "loongarch64"89 )90 )))]91 pub fn new() -> Self {92 Self {93 events: Default::default(),94 }95 }9697 /// Read raw counts after the child has exited. Like poop, do not scale for multiplexing.98 pub fn read(mut self) -> HardwareCounters {99 let [cpu_cycles, instructions, cache_references, cache_misses, branch_misses] =100 self.events.each_mut().map(|event| {101 let mut bytes = [0; 8];102 event.as_mut()?.read_exact(&mut bytes).ok()?;103 Some(u64::from_ne_bytes(bytes))104 });105 HardwareCounters {106 cpu_cycles,107 instructions,108 cache_references,109 cache_misses,110 branch_misses,111 }112 }113}
added:src/timer/macos_counters.rs+55 added
1use std::io;2use std::mem::MaybeUninit;3use std::process::Child;45use crate::benchmark::measurement::HardwareCounters;67/// Wait for exit without reaping: proc_pid_rusage can still inspect the zombie,8/// and the existing wait4 call can subsequently collect CPU times and peak RSS.9pub fn wait(child: &mut Child) -> io::Result<()> {10 drop(child.stdin.take());11 let mut info = MaybeUninit::uninit();12 loop {13 // SAFETY: info points to writable siginfo_t storage. WNOWAIT preserves the child.14 let result = unsafe {15 libc::waitid(16 libc::P_PID,17 child.id(),18 info.as_mut_ptr(),19 libc::WEXITED | libc::WNOWAIT,20 )21 };22 if result == 0 {23 return Ok(());24 }25 let error = io::Error::last_os_error();26 if error.kind() != io::ErrorKind::Interrupted {27 return Err(error);28 }29 }30}3132pub fn read(pid: u32) -> HardwareCounters {33 let mut usage = MaybeUninit::<libc::rusage_info_v4>::zeroed();34 // SAFETY: the buffer has the layout and size requested by RUSAGE_INFO_V4.35 // Despite the pointer-to-pointer signature, this API writes directly into the buffer.36 let result = unsafe {37 libc::proc_pid_rusage(38 pid as libc::pid_t,39 libc::RUSAGE_INFO_V4,40 usage.as_mut_ptr().cast(),41 )42 };43 if result != 0 {44 return HardwareCounters::default();45 }46 // SAFETY: the call succeeded and initialized the buffer.47 let usage = unsafe { usage.assume_init() };48 HardwareCounters {49 // Like macOS time(1), omit zero counters: the API can succeed on systems50 // where instruction/cycle accounting is unavailable.51 cpu_cycles: (usage.ri_cycles != 0).then_some(usage.ri_cycles),52 instructions: (usage.ri_instructions != 0).then_some(usage.ri_instructions),53 ..Default::default()54 }55}
modified:src/timer/mod.rs+33 added-1 removed
1mod wall_clock_timer;23#[cfg(target_os = "linux")]4mod linux_counters;5#[cfg(target_os = "macos")]6mod macos_counters;78#[cfg(windows)]9mod windows_timer;1011#[cfg(not(windows))]
48 unmodified lines
60 }61}6263/// Execute the given command and return a timing summary59pub fn execute_and_measure(mut command: Command) -> Result<Measurement> {64pub fn execute_and_measure(65 mut command: Command,66 _collect_hardware_counters: bool,67) -> Result<Measurement> {68 #[cfg(target_os = "linux")]69 let counters = _collect_hardware_counters.then(linux_counters::CounterGroup::new);70 #[cfg(not(windows))]71 let cpu_timer = self::unix_timer::CPUTimer::start();7273 #[cfg(windows)]
17 unmodified lines
91 // Handle CommandOutputPolicy::Pipe92 discard(output);93 }9495 #[cfg(target_os = "macos")]96 let (time_wall_clock, hardware_counters) =97 if _collect_hardware_counters && macos_counters::wait(&mut child).is_ok() {98 // Stop timing before querying counters, but leave the child available for wait4.99 (100 Some(wallclock_timer.stop()),101 macos_counters::read(child.id()),102 )103 } else {104 (None, Default::default())105 };106 let (time_user, time_system, memory_peak_resident, exit_status) = cpu_timer.stop(child)?;107 #[cfg(target_os = "macos")]108 let time_wall_clock = time_wall_clock.unwrap_or_else(|| wallclock_timer.stop());109 #[cfg(not(target_os = "macos"))]110 let time_wall_clock = wallclock_timer.stop();111112 #[cfg(target_os = "linux")]113 let hardware_counters = counters114 .map(linux_counters::CounterGroup::read)115 .unwrap_or_default();116 #[cfg(not(any(target_os = "linux", target_os = "macos")))]117 let hardware_counters = Default::default();118119 Ok(Measurement {120 time_wall_clock,121 time_user,122 time_system,123 memory_peak_resident,124 hardware_counters,125 exit_status,126 })127}
modified:Cargo.lock+10 added
391 unmodified lines
392 "insta-cmd",393 "libc",394 "nix",395 "once_cell",396 "perf-event-open-sys",397 "platform-info",398 "predicates",399 "rand 0.10.3",400 "rust_decimal",
139 unmodified lines
540source = "registry+https://github.com/rust-lang/crates.io-index"541checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"542543[[package]]544name = "perf-event-open-sys"545version = "6.0.0"546source = "registry+https://github.com/rust-lang/crates.io-index"547checksum = "a5f8d1487a4ffa23c80a1c355dd27235f9b66fb71ba0f261eb417e4fe8451347"548dependencies = [549 "libc",550]551552[[package]]553name = "platform-info"554version = "2.2.0"555source = "registry+https://github.com/rust-lang/crates.io-index"556checksum = "ba7c3f5af00d3596a148cc80178ac690152b71c283d15a8bcea0cddfea759a36"
654 unmodified lines
modified:Cargo.toml+3 added
48 unmodified lines
4950[target.'cfg(target_os="linux")'.dependencies]51nix = { version = "0.31", features = ["zerocopy"] }5253[target.'cfg(all(target_os = "linux", target_pointer_width = "64", any(target_arch = "aarch64", target_arch = "x86_64", target_arch = "riscv64", target_arch = "powerpc64", target_arch = "loongarch64")))'.dependencies]54perf-event-open-sys = "6"5556[dependencies.clap]57version = "4"58default-features = false59features = [
29 unmodified lines
modified:README.md+28 added
185 unmodified lines
186 command and child processes (whose usage is collected when their parents wait for them),187 *not the simultaneous total memory of the full process tree*.188 - Windows: Currently not supported.189190- **`cpu_cycles`**: CPU cycles consumed.191192 - Linux: Includes threads and child processes, but excludes kernel and hypervisor execution.193 - macOS: Includes the process's threads and kernel execution, but excludes child processes.194 - Windows: Currently not supported.195196- **`instructions`**: Completed CPU instructions.197198 - Linux/macOS: Same scope as `cpu_cycles`.199 - Windows: Currently not supported.200201- **`cache_references`**: Cache accesses counted by the CPU's generic cache event.202203 - Linux: Same scope as `cpu_cycles`. Cache-event definitions depend on the CPU.204 - macOS/Windows: Currently not supported.205206- **`cache_misses`**: Cache misses.207208 - Linux: Same scope as `cpu_cycles`. Cache-event definitions depend on the CPU.209 - macOS/Windows: Currently not supported.210211- **`branch_misses`**: Mispredicted branches.212213 - Linux: Same scope as `cpu_cycles`.214 - macOS/Windows: Currently not supported.215216Hardware counters are not available if a `--shell` is used.217218The JSON output is useful if you want to analyze the benchmark results in more detail. The219[`scripts/`](https://github.com/sharkdp/hyperfine/tree/master/scripts) folder includes a lot220of helpful Python programs to further analyze benchmark results and create helpful221visualizations, like a histogram of runtimes or a whisker plot to compare
190 unmodified lines