Skip to content

Commit b029a18

Browse files
committed
extra::test: add an opaque function to assist with accurate
benchmarking. This allows a result to be marked as "used" by passing it to a function LLVM cannot see inside. By making `iter` generic and using this `black_box` on the result benchmarks can get this behaviour simply by returning their computation.
1 parent b60bed9 commit b029a18

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

src/libextra/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ Rust extras are part of the standard Rust distribution.
2929
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
3030
html_root_url = "http://static.rust-lang.org/doc/master")];
3131

32-
#[feature(macro_rules, globs, managed_boxes)];
32+
#[feature(macro_rules, globs, managed_boxes, asm)];
3333

3434
#[deny(non_camel_case_types)];
3535
#[deny(missing_doc)];

src/libextra/test.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1091,13 +1091,25 @@ impl MetricMap {
10911091
10921092
// Benchmarking
10931093
1094+
/// A function that is opaque to the optimiser, to allow benchmarks to
1095+
/// pretend to use outputs to assist in avoiding dead-code
1096+
/// elimination.
1097+
///
1098+
/// This function is a no-op, and does not even read from `dummy`.
1099+
pub fn black_box<T>(dummy: T) {
1100+
// we need to "use" the argument in some way LLVM can't
1101+
// introspect.
1102+
unsafe {asm!("" : : "r"(&dummy))}
1103+
}
1104+
1105+
10941106
impl BenchHarness {
10951107
/// Callback for benchmark functions to run in their body.
1096-
pub fn iter(&mut self, inner: ||) {
1108+
pub fn iter<T>(&mut self, inner: || -> T) {
10971109
self.ns_start = precise_time_ns();
10981110
let k = self.iterations;
10991111
for _ in range(0u64, k) {
1100-
inner();
1112+
black_box(inner());
11011113
}
11021114
self.ns_end = precise_time_ns();
11031115
}

0 commit comments

Comments
 (0)