iai-0.1.1/.cargo_vcs_info.json0000644000000001121400331330000116100ustar { "git": { "sha1": "935caf10b0bed2d89c31e9a7486cd4bbfbc07252" } } iai-0.1.1/.github/workflows/ci.yml010077700017500001750000000024221377441207300151660ustar 00000000000000on: [push, pull_request] name: Continuous integration jobs: ci: runs-on: ubuntu-latest strategy: matrix: rust: - stable - beta - nightly - 1.45.0 # MSRV steps: - run: sudo apt-get update - run: sudo apt install -y valgrind - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: ${{ matrix.rust }} override: true - run: cargo bench - if: ${{ matrix.rust == 'nightly' }} working-directory: ./macro run: cargo bench lint: strategy: matrix: rust: - stable - nightly runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: ${{ matrix.rust }} override: true components: rustfmt, clippy - run: cargo fmt --all -- --check - run: cargo clippy --all -- -D warnings - if: ${{ matrix.rust == 'nightly' }} working-directory: ./macro run: cargo fmt --all -- --check - if: ${{ matrix.rust == 'nightly' }} working-directory: ./macro run: cargo clippy --all -- -D warnings iai-0.1.1/.gitignore010077700017500001750000000000231377414231300124330ustar 00000000000000/target Cargo.lock iai-0.1.1/CHANGELOG.md010077700017500001750000000005541377415707700123020ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). ## [Unreleased] ### Added - Initial implementation. [Unreleased]: https://github.com/bheisler/iai/compare/...HEADiai-0.1.1/CONTRIBUTING.md010077700017500001750000000050761377416553400127230ustar 00000000000000# Contributing to Iai ## Ideas, Experiences and Questions The easiest way to contribute to Iai is to use it and report your experiences, ask questions and contribute ideas. We'd love to hear your thoughts on how to make Iai better, or your comments on why you are or are not currently using it. Issues, ideas, requests and questions should be posted on the issue tracker at: https://github.com/bheisler/iai/issues ## A Note on Dependency Updates Iai does not accept pull requests to update dependencies unless specifically requested by the maintaner(s). Dependencies are updated manually by the maintainer(s) before each new release. ## Code Pull requests are welcome, though please raise an issue for discussion first if none exists. We're happy to assist new contributors. If you're not sure what to work on, try checking the [Beginner label](https://github.com/bheisler/iai/issues?q=is%3Aissue+is%3Aopen+label%3ABeginner) To make changes to the code, fork the repo and clone it: `git clone git@github.com:your-username/iai.git` Then make your changes to the code. When you're done, run the tests: ``` cargo test --all cargo bench ``` It's a good idea to run clippy and fix any warnings as well: ``` rustup component add clippy-preview cargo clippy --all ``` Finally, run Rustfmt to maintain a common code style: ``` rustup component add rustfmt-preview cargo fmt --all ``` Don't forget to update the CHANGELOG.md file and any appropriate documentation. Once you're finished, push to your fork and submit a pull request. We try to respond to new issues and pull requests quickly, so if there hasn't been any response for more than a few days feel free to ping @bheisler. Some things that will increase the chance that your pull request is accepted: * Write tests * Clearly document public methods * Write a good commit message ## Github Labels Iai uses a simple set of labels to track issues. Most important are the difficulty labels: * Beginner - Suitable for people new to Criterion.rs, or even new to Rust in general * Intermediate - More challenging, likely involves some non-trivial design decisions and/or knowledge of Iai's internals * Bigger Project - Large and/or complex project such as designing a complex new feature. Additionally, there are a few other noteworthy labels: * Breaking Change - Fixing this will have to wait until the next breaking-change release * Bug - Something isn't working right * Enhancement - Request to add a new feature or otherwise improve Iai in some way ## Code of Conduct We follow the [Rust Code of Conduct](http://www.rust-lang.org/conduct.html). iai-0.1.1/Cargo.toml0000644000000020121400331330000076070ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "iai" version = "0.1.1" authors = ["Brook Heisler "] description = "One-shot benchmarking library" readme = "README.md" keywords = ["iai", "benchmark"] categories = ["development-tools::profiling"] license = "Apache-2.0/MIT" repository = "https://github.com/bheisler/iai" [[bench]] name = "test_regular_bench" harness = false [dependencies.iai_macro] version = "0.1.0" optional = true [features] default = [] macro = ["iai_macro"] real_blackbox = [] iai-0.1.1/Cargo.toml.orig010077700017500001750000000010251400331324100133170ustar 00000000000000[package] name = "iai" version = "0.1.1" authors = ["Brook Heisler "] edition = "2018" description = "One-shot benchmarking library" repository = "https://github.com/bheisler/iai" readme = "README.md" keywords = ["iai", "benchmark"] categories = ["development-tools::profiling"] license = "Apache-2.0/MIT" [dependencies] iai_macro = { version = "0.1.0", path = "macro", optional = true } [features] real_blackbox = [] macro = ["iai_macro"] default = [] [[bench]] name = "test_regular_bench" harness = falseiai-0.1.1/LICENSE-APACHE010077700017500001750000000251371377415674300124200ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. iai-0.1.1/LICENSE-MIT010077700017500001750000000020421377415674300121160ustar 00000000000000Copyright (c) 2014 Jorge Aparicio Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. iai-0.1.1/README.md010077700017500001750000000161071400331254700117260ustar 00000000000000

Iai

Experimental One-shot Benchmark Framework in Rust
Continuous integration
Getting Started | User Guide | Released API Docs | Changelog
Iai is an experimental benchmarking harness that uses Cachegrind to perform extremely precise single-shot measurements of Rust code. ## Table of Contents - [Table of Contents](#table-of-contents) - [Features](#features) - [Quickstart](#quickstart) - [Goals](#goals) - [Comparison with Criterion-rs](#comparison-with-criterion-rs) - [Contributing](#contributing) - [Compatibility Policy](#compatibility-policy) - [Maintenance](#maintenance) - [License](#license) ### Features - __Precision__: High-precision measurements allow you to reliably detect very small optimizations to your code - __Consistency__: Iai can take accurate measurements even in virtualized CI environments - __Performance__: Since Iai only executes a benchmark once, it is typically faster to run than statistical benchmarks - __Profiling__: Iai generates a Cachegrind profile of your code while benchmarking, so you can use Cachegrind-compatible tools to analyze the results in detail - __Stable-compatible__: Benchmark your code without installing nightly Rust ### Quickstart In order to use Iai, you must have [Valgrind] installed. This means that Iai cannot be used on platforms that are not supported by Valgrind. [Valgrind]: https://www.valgrind.org To start with Iai, add the following to your `Cargo.toml` file: ```toml [dev-dependencies] iai = "0.1" [[bench]] name = "my_benchmark" harness = false ``` Next, define a benchmark by creating a file at `$PROJECT/benches/my_benchmark.rs` with the following contents: ```rust use iai::{black_box, main}; fn fibonacci(n: u64) -> u64 { match n { 0 => 1, 1 => 1, n => fibonacci(n-1) + fibonacci(n-2), } } fn iai_benchmark_short() -> u64 { fibonacci(black_box(10)) } fn iai_benchmark_long() -> u64 { fibonacci(black_box(30)); } iai::main!(iai_benchmark_short, iai_benchmark_long); ``` Finally, run this benchmark with `cargo bench`. You should see output similar to the following: ``` Running target/release/deps/test_regular_bench-8b173c29ce041afa bench_fibonacci_short Instructions: 1735 L1 Accesses: 2364 L2 Accesses: 1 RAM Accesses: 1 Estimated Cycles: 2404 bench_fibonacci_long Instructions: 26214735 L1 Accesses: 35638623 L2 Accesses: 2 RAM Accesses: 1 Estimated Cycles: 35638668 ``` ### Goals The primary goal of Iai is to provide a simple and precise tool for reliably detecting very small changes to the performance of code. Additionally, it should be as programmer-friendly as possible and make it easy to create reliable, useful benchmarks. ### Comparison with Criterion-rs I intend Iai to be a complement to Criterion-rs, not a competitor. The two projects measure different things in different ways and have different pros, cons, and limitations, so for most projects the best approach is to use both. Here's an overview of the important differences: - Temporary Con: Right now, Iai is lacking many features of Criterion-rs, including reports and configuration of any kind. - The current intent is to add support to [Cargo-criterion] for configuring and reporting on Iai benchmarks. - Pro: Iai can reliably detect much smaller changes in performance than Criterion-rs can. - Pro: Iai can work reliably in noisy CI environments or even cloud CI providers like GitHub Actions or Travis-CI, where Criterion-rs cannot. - Pro: Iai also generates profile output from the benchmark without further effort. - Pro: Although Cachegrind adds considerable runtime overhead, running each benchmark exactly once is still usually faster than Criterion-rs' statistical measurements. - Mixed: Because Iai can detect such small changes, it may report performance differences from changes to the order of functions in memory and other compiler details. - Con: Iai's measurements merely correlate with wall-clock time (which is usually what you actually care about), where Criterion-rs measures it directly. - Con: Iai cannot exclude setup code from the measurements, where Criterion-rs can. - Con: Because Cachegrind does not measure system calls, IO time is not accurately measured. - Con: Because Iai runs the benchmark exactly once, it cannot measure variation in the performance such as might be caused by OS thread scheduling or hash-table randomization. - Limitation: Iai can only be used on platforms supported by Valgrind. Notably, this does not include Windows. For benchmarks that run in CI (especially if you're checking for performance regressions in pull requests on cloud CI) you should use Iai. For benchmarking on Windows or other platforms that Valgrind doesn't support, you should use Criterion-rs. For other cases, I would advise using both. Iai gives more precision and scales better to larger benchmarks, while Criterion-rs allows for excluding setup time and gives you more information about the actual time your code takes and how strongly that is affected by non-determinism like threading or hash-table randomization. If you absolutely need to pick one or the other though, Iai is probably the one to go with. [Cargo-criterion]: https://github.com/bheisler/cargo-criterion ### Contributing First, thank you for contributing. One great way to contribute to Iai is to use it for your own benchmarking needs and report your experiences, file and comment on issues, etc. Code or documentation improvements in the form of pull requests are also welcome. If you're not sure what to work on, try checking the [Beginner label](https://github.com/bheisler/iai/issues?q=is%3Aissue+is%3Aopen+label%3ABeginner). If your issues or pull requests have no response after a few days, feel free to ping me (@bheisler). For more details, see the [CONTRIBUTING.md file](https://github.com/bheisler/iai/blob/master/CONTRIBUTING.md). ### Compatibility Policy Iai supports the last three stable minor releases of Rust. At time of writing, this means Rust 1.48 or later. Older versions may work, but are not tested or guaranteed. Currently, the oldest version of Rust believed to work is 1.48. Future versions of Iai may break support for versions older than 3-versions-ago, and this will not be considered a breaking change. If you require Iai to work on old versions of Rust, you will need to stick to a specific patch version of Iai. ### Maintenance Iai was originally written and is maintained by Brook Heisler (@bheisler) ### License Iai is dual licensed under the Apache 2.0 license and the MIT license. iai-0.1.1/benches/test_regular_bench.rs010077700017500001750000000006111377415071000162620ustar 00000000000000use iai::black_box; fn fibonacci(n: u64) -> u64 { match n { 0 | 1 => 1, n => fibonacci(n - 1) + fibonacci(n - 2), } } fn bench_empty() { return; } fn bench_fibonacci() -> u64 { fibonacci(black_box(10)) } fn bench_fibonacci_long() -> u64 { fibonacci(black_box(30)) } iai::main!(bench_empty, bench_fibonacci, bench_fibonacci_long); iai-0.1.1/src/lib.rs010077700017500001750000000272051400331324500123470ustar 00000000000000#![cfg_attr(feature = "real_blackbox", feature(test))] #[cfg(feature = "real_blackbox")] extern crate test; use std::{ collections::HashMap, env::args, fs::File, io::{BufRead, BufReader}, path::{Path, PathBuf}, process::{Command, Stdio}, }; #[cfg(feature = "macro")] pub use iai_macro::iai; mod macros; /// A function that is opaque to the optimizer, used to prevent the compiler from /// optimizing away computations in a benchmark. /// /// This variant is backed by the (unstable) test::black_box function. #[cfg(feature = "real_blackbox")] pub fn black_box(dummy: T) -> T { test::black_box(dummy) } /// A function that is opaque to the optimizer, used to prevent the compiler from /// optimizing away computations in a benchmark. /// /// This variant is stable-compatible, but it may cause some performance overhead /// or fail to prevent code from being eliminated. #[cfg(not(feature = "real_blackbox"))] pub fn black_box(dummy: T) -> T { unsafe { let ret = std::ptr::read_volatile(&dummy); std::mem::forget(dummy); ret } } fn check_valgrind() -> bool { let result = Command::new("valgrind") .arg("--tool=cachegrind") .arg("--version") .stdout(Stdio::null()) .stderr(Stdio::null()) .status(); match result { Err(e) => { println!("Unexpected error while launching valgrind. Error: {}", e); false } Ok(status) => { if status.success() { true } else { println!("Failed to launch valgrind. Error: {}. Please ensure that valgrind is installed and on the $PATH.", status); false } } } } fn get_arch() -> String { let output = Command::new("uname") .arg("-m") .stdout(Stdio::piped()) .output() .expect("Failed to run `uname` to determine CPU architecture."); String::from_utf8(output.stdout) .expect("`-uname -m` returned invalid unicode.") .trim() .to_owned() } fn run_bench( arch: &str, executable: &str, i: isize, name: &str, ) -> (CachegrindStats, Option) { let output_file = PathBuf::from(format!("target/iai/cachegrind.out.{}", name)); let old_file = output_file.with_file_name(format!("cachegrind.out.{}.old", name)); std::fs::create_dir_all(output_file.parent().unwrap()).expect("Failed to create directory"); if output_file.exists() { // Already run this benchmark once; move last results to .old std::fs::copy(&output_file, &old_file).unwrap(); } // Run under setarch to disable ASLR, which could noise up the results a bit let mut cmd = Command::new("setarch"); let status = cmd .arg(arch) .arg("-R") .arg("valgrind") .arg("--tool=cachegrind") // Set some reasonable cache sizes. The exact sizes matter less than having fixed sizes, // since otherwise cachegrind would take them from the CPU and make benchmark runs // even more incomparable between machines. .arg("--I1=32768,8,64") .arg("--D1=32768,8,64") .arg("--LL=8388608,16,64") .arg(format!("--cachegrind-out-file={}", output_file.display())) .arg(executable) .arg("--iai-run") .arg(i.to_string()) .stdout(Stdio::null()) .stderr(Stdio::null()) .status() .expect("Failed to run benchmark in cachegrind"); if !status.success() { panic!( "Failed to run benchmark in cachegrind. Exit code: {}", status ); } let new_stats = parse_cachegrind_output(&output_file); let old_stats = if old_file.exists() { Some(parse_cachegrind_output(&old_file)) } else { None }; (new_stats, old_stats) } fn parse_cachegrind_output(file: &Path) -> CachegrindStats { let mut events_line = None; let mut summary_line = None; let file_in = File::open(file).expect("Unable to open cachegrind output file"); for line in BufReader::new(file_in).lines() { let line = line.unwrap(); if let Some(line) = line.strip_prefix("events: ") { events_line = Some(line.trim().to_owned()); } if let Some(line) = line.strip_prefix("summary: ") { summary_line = Some(line.trim().to_owned()); } } match (events_line, summary_line) { (Some(events), Some(summary)) => { let events: HashMap<_, _> = events .split_whitespace() .zip(summary.split_whitespace().map(|s| { s.parse::() .expect("Unable to parse summary line from cachegrind output file") })) .collect(); CachegrindStats { instruction_reads: events["Ir"], instruction_l1_misses: events["I1mr"], instruction_cache_misses: events["ILmr"], data_reads: events["Dr"], data_l1_read_misses: events["D1mr"], data_cache_read_misses: events["DLmr"], data_writes: events["Dw"], data_l1_write_misses: events["D1mw"], data_cache_write_misses: events["DLmw"], } } _ => panic!("Unable to parse cachegrind output file"), } } #[derive(Clone, Debug)] struct CachegrindStats { instruction_reads: u64, instruction_l1_misses: u64, instruction_cache_misses: u64, data_reads: u64, data_l1_read_misses: u64, data_cache_read_misses: u64, data_writes: u64, data_l1_write_misses: u64, data_cache_write_misses: u64, } impl CachegrindStats { pub fn ram_accesses(&self) -> u64 { self.instruction_cache_misses + self.data_cache_read_misses + self.data_cache_write_misses } pub fn summarize(&self) -> CachegrindSummary { let ram_hits = self.ram_accesses(); let l3_accesses = self.instruction_l1_misses + self.data_l1_read_misses + self.data_l1_write_misses; let l3_hits = l3_accesses - ram_hits; let total_memory_rw = self.instruction_reads + self.data_reads + self.data_writes; let l1_hits = total_memory_rw - (ram_hits + l3_hits); CachegrindSummary { l1_hits, l3_hits, ram_hits, } } #[rustfmt::skip] pub fn subtract(&self, calibration: &CachegrindStats) -> CachegrindStats { CachegrindStats { instruction_reads: self.instruction_reads.saturating_sub(calibration.instruction_reads), instruction_l1_misses: self.instruction_l1_misses.saturating_sub(calibration.instruction_l1_misses), instruction_cache_misses: self.instruction_cache_misses.saturating_sub(calibration.instruction_cache_misses), data_reads: self.data_reads.saturating_sub(calibration.data_reads), data_l1_read_misses: self.data_l1_read_misses.saturating_sub(calibration.data_l1_read_misses), data_cache_read_misses: self.data_cache_read_misses.saturating_sub(calibration.data_cache_read_misses), data_writes: self.data_writes.saturating_sub(calibration.data_writes), data_l1_write_misses: self.data_l1_write_misses.saturating_sub(calibration.data_l1_write_misses), data_cache_write_misses: self.data_cache_write_misses.saturating_sub(calibration.data_cache_write_misses), } } } #[derive(Clone, Debug)] struct CachegrindSummary { l1_hits: u64, l3_hits: u64, ram_hits: u64, } impl CachegrindSummary { fn cycles(&self) -> u64 { // Uses Itamar Turner-Trauring's formula from https://pythonspeed.com/articles/consistent-benchmarking-in-ci/ self.l1_hits + (5 * self.l3_hits) + (35 * self.ram_hits) } } /// Custom-test-framework runner. Should not be called directly. #[doc(hidden)] pub fn runner(benches: &[&(&'static str, fn())]) { let mut args_iter = args(); let executable = args_iter.next().unwrap(); if let Some("--iai-run") = args_iter.next().as_deref() { // In this branch, we're running under cachegrind, so execute the benchmark as quickly as // possible and exit let index: isize = args_iter.next().unwrap().parse().unwrap(); // -1 is used as a signal to do nothing and return. By recording an empty benchmark, we can // subtract out the overhead from startup and dispatching to the right benchmark. if index == -1 { return; } let index = index as usize; (benches[index].1)(); return; } // Otherwise we're running normally, under cargo if !check_valgrind() { return; } let arch = get_arch(); let (calibration, old_calibration) = run_bench(&arch, &executable, -1, "iai_calibration"); for (i, (name, _func)) in benches.iter().enumerate() { println!("{}", name); let (stats, old_stats) = run_bench(&arch, &executable, i as isize, name); let (stats, old_stats) = ( stats.subtract(&calibration), match (&old_stats, &old_calibration) { (Some(old_stats), Some(old_calibration)) => { Some(old_stats.subtract(old_calibration)) } _ => None, }, ); fn signed_short(n: f64) -> String { let n_abs = n.abs(); if n_abs < 10.0 { format!("{:+.6}", n) } else if n_abs < 100.0 { format!("{:+.5}", n) } else if n_abs < 1000.0 { format!("{:+.4}", n) } else if n_abs < 10000.0 { format!("{:+.3}", n) } else if n_abs < 100000.0 { format!("{:+.2}", n) } else if n_abs < 1000000.0 { format!("{:+.1}", n) } else { format!("{:+.0}", n) } } fn percentage_diff(new: u64, old: u64) -> String { if new == old { return " (No change)".to_owned(); } let new: f64 = new as f64; let old: f64 = old as f64; let diff = (new - old) / old; let pct = diff * 100.0; format!(" ({:>+6}%)", signed_short(pct)) } println!( " Instructions: {:>15}{}", stats.instruction_reads, match &old_stats { Some(old) => percentage_diff(stats.instruction_reads, old.instruction_reads), None => "".to_owned(), } ); let summary = stats.summarize(); let old_summary = old_stats.map(|stat| stat.summarize()); println!( " L1 Accesses: {:>15}{}", summary.l1_hits, match &old_summary { Some(old) => percentage_diff(summary.l1_hits, old.l1_hits), None => "".to_owned(), } ); println!( " L2 Accesses: {:>15}{}", summary.l3_hits, match &old_summary { Some(old) => percentage_diff(summary.l3_hits, old.l3_hits), None => "".to_owned(), } ); println!( " RAM Accesses: {:>15}{}", summary.ram_hits, match &old_summary { Some(old) => percentage_diff(summary.ram_hits, old.ram_hits), None => "".to_owned(), } ); println!( " Estimated Cycles: {:>15}{}", summary.cycles(), match &old_summary { Some(old) => percentage_diff(summary.cycles(), old.cycles()), None => "".to_owned(), } ); println!(); } } iai-0.1.1/src/macros.rs010077700017500001750000000026741377415254400131110ustar 00000000000000//! Contains macros which together define a benchmark harness that can be used //! in place of the standard benchmark harness. This allows the user to run //! Iai benchmarks with `cargo bench`. /// Macro which expands to a benchmark harness. /// /// Currently, using Iai requires disabling the benchmark harness /// generated automatically by rustc. This can be done like so: /// /// ```toml /// [[bench]] /// name = "my_bench" /// harness = false /// ``` /// /// In this case, `my_bench` must be a rust file inside the 'benches' directory, /// like so: /// /// `benches/my_bench.rs` /// /// Since we've disabled the default benchmark harness, we need to add our own: /// /// ```ignore /// fn bench_method1() { /// } /// /// fn bench_method2() { /// } /// /// iai::main!(bench_method1, bench_method2); /// ``` /// /// The `iai::main` macro expands to a `main` function which runs all of the /// benchmarks in the given groups. /// #[macro_export] macro_rules! main { ( $( $func_name:ident ),+ $(,)* ) => { mod iai_wrappers { $( pub fn $func_name() { let _ = $crate::black_box(super::$func_name()); } )+ } fn main() { let benchmarks : &[&(&'static str, fn())]= &[ $( &(stringify!($func_name), iai_wrappers::$func_name), )+ ]; $crate::runner(benchmarks); } } }