Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

black_box improvements #1

Open
wants to merge 3 commits into
base: benchmarking
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 48 additions & 2 deletions text/0000-benchmarking.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,33 @@ fn my_benchmark(bench: Bencher) -> BenchResult {
bench.iter(|| {
black_box(pow(y, x));
pow(x, y)
});
})
}
```

In case you want the benchmark to run for a predetermined number of times, use `iter_n`:

```rust
#[bench]
fn my_benchmark(bench: Bencher) -> BenchResult {
bench.iter_n(1000, || do_some_stuff());
}
```

Using `mem::clobber()` you can force the optimizer to flush all pending writes
to memory of data previously passed to `mem::black_box`:

```rust
fn bench_vec_push_back(bench: Bencher) -> BenchResult {
let n = 100_000_000;
let mut v = Vec::with_capacity(n);
bench.iter_n(n, || {
// Allow vector data to be clobbered:
mem::black_box(v.as_ptr());
v.push_back(42_u8);
// Forces 42 to be written back to memory:
mem::clobber();
})
}
```

Expand All @@ -120,8 +146,28 @@ Samples are [winsorized], so extreme outliers get clamped.
`cargo bench` essentially takes the same flags as `cargo test`, except it has a `--bench foo`
flag to select a single benchmark target.

[winsorized]: https://en.wikipedia.org/wiki/Winsorizing

## `mem::black_box`

```rust
pub fn black_box<T>(x: T) -> T;
```

Prevents a value or the result of an expression from being optimized away by the
compiler adding as little overhead as possible. It does not prevent
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also mention that it prevents outer code from "seeing" the inside optimization-wise -- values produced by black_box are from the optimizer's perspective no different from being random.

optimizations on the expression generating the value in any way: the expression
might be removed entirely when the result is already known. It forces, however,
the result of the expression to be stored in either memory or a register.

## `mem::clobber`

```rust
pub fn clobber() -> ();
```

[winsorized]: https://en.wikipedia.org/wiki/Winsorizing
Is a read/write barrier: it flushes pending writes to variables "escaped" with
`mem::black_box` to global memory.

# Drawbacks
[drawbacks]: #drawbacks
Expand Down