Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

bench: Generate random acceses in Wasm for builtin benchmark (#14281)

Adam Bratschi-Kaye4675ee16b703
diff --git a/benches/compile_time_builtins.rs b/benches/compile_time_builtins.rs
index 867bd703dd..708596aa38 100644
--- a/benches/compile_time_builtins.rs
+++ b/benches/compile_time_builtins.rs
@@ -4,7 +4,22 @@ use criterion::{Bencher, Criterion, criterion_group, criterion_main};
use std::{mem, time::Instant};
use wasmtime::{component::Component, *};
-const HOST_BUF_LEN: usize = 100_000;
+// The nearest power of two to 100,000 (2^17 = 131_072). Using a power of two
+// lets the PRNG's high bits map directly onto the buffer without division.
+const HOST_BUF_LEN: usize = 1 << 17;
+
+// We'll generate random indices of the buffer by taking the high bits from a
+// multiplicative congruence generator modulo 2^64. So we'll get the sequence
+// x_0, x_1, ... where x_n+1 = a * x_n mod 2^64 and the nth buffer access will
+// be at index x_n > 17.
+//
+// Recommended as a "good" multiplier by Steele and Vigna mod 2^64 (see
+// https://arxiv.org/pdf/2001.05304, page 18, table 7).
+const MCG_MULTIPLIER: u64 = 0xf1357aea2e62a9c5;
+const MCG_SEED: u64 = 1;
+// The shift required to take the highest bits of a u64 get an index to the
+// buffer.
+const MCG_OUTPUT_SHIFT: u32 = u64::BITS - HOST_BUF_LEN.trailing_zeros();
/// A `*mut u8` pointer that is exposed directly to Wasm via unsafe intrinsics.
#[repr(align(8))]
@@ -395,7 +410,7 @@ mod inc_list {
static TAKE_AND_RETURN_INT_LIST_GUEST_WASM: &str = r#"
(component
(core module $m
- (memory (export "memory") 2)
+ (memory (export "memory") 3)
(func (export "realloc") (param i32 i32 i32 i32) (result i32)
;; Reserve the first two `u32`s of memory for the return-values buffer.
(i32.const 8)
@@ -493,7 +508,9 @@ mod inc_random {
});
}
- static HOST_BUF_API_GUEST_WASM: &str = r#"
+ fn host_buf_api_guest_wasm() -> String {
+ format!(
+ r#"
(component
;; Import the safe API.
(import "host-buf"
@@ -508,10 +525,39 @@ mod inc_random {
(import "" "get" (func $get (param i64) (result i32)))
(import "" "set" (func $set (param i64 i32)))
- (func (export "inc-random") (param $i i64)
- (call $set (local.get $i)
- (i32.add (call $get (local.get $i))
- (i32.const 1)))
+ (func (export "inc-random")
+ (param $iters i64)
+ (local $state i64)
+ (local $i i64)
+
+ (local.set $state (i64.const {MCG_SEED}))
+ loop $l
+ ;; Take the highest bits of random state for the index.
+ (local.set $i
+ (i64.shr_u
+ (local.get $state)
+ (i64.const {MCG_OUTPUT_SHIFT})
+ )
+ )
+ ;; Increment the buffer.
+ (call $set (local.get $i)
+ (i32.add (call $get (local.get $i))
+ (i32.const 1)))
+ (local.set $iters (i64.sub (local.get $iters) (i64.const 1)))
+ local.get $iters
+ i64.eqz
+ if
+ return
+ end
+ ;; Get next random number by multiplying by multiplier.
+ (local.set $state
+ (i64.mul
+ (local.get $state)
+ (i64.const {MCG_MULTIPLIER})
+ )
+ )
+ br $l
+ end
)
)
@@ -531,11 +577,13 @@ mod inc_random {
;; Lift the implementation's `inc-random` from a core function to a component function
;; and export it!
- (func (export "inc-random") (param "i" u64)
+ (func (export "inc-random") (param "iters" u64)
(canon lift (core func $instance "inc-random"))
)
)
- "#;
+ "#
+ )
+ }
fn get_random_index() -> Result<u64, Error> {
let mut rng = rand::rngs::SmallRng::seed_from_u64(42);
@@ -544,10 +592,22 @@ mod inc_random {
Ok(i)
}
+ fn get_expected(iters: u64) -> Vec<u8> {
+ let mut state = MCG_SEED;
+ let mut buf = vec![0u8; HOST_BUF_LEN];
+ for _ in 0..iters {
+ let i = usize::try_from(state >> MCG_OUTPUT_SHIFT).unwrap();
+ buf[i] = buf[i].wrapping_add(1);
+ state = state.wrapping_mul(MCG_MULTIPLIER);
+ }
+ buf
+ }
+
fn func_wrap_host_buf_api(b: &mut Bencher<'_>, concurrency_support: bool) -> Result<()> {
let engine = make_engine(concurrency_support)?;
let linker = make_linker(&engine)?;
- let component = Component::new(&engine, HOST_BUF_API_GUEST_WASM.as_bytes())?;
+ let guest_wasm = host_buf_api_guest_wasm();
+ let component = Component::new(&engine, guest_wasm.as_bytes())?;
let iter_func = |iters| -> Result<_> {
let mut store = Store::new(
@@ -556,20 +616,14 @@ mod inc_random {
);
let instance = linker.instantiate(&mut store, &component)?;
let inc_random = instance.get_typed_func::<(u64,), ()>(&mut store, "inc-random")?;
- let i = get_random_index()?;
let start = Instant::now();
- for _ in 0..iters {
- inc_random.call(&mut store, (i,))?;
- }
+ inc_random.call(&mut store, (iters,))?;
let elapsed = start.elapsed();
- let expected = iters as u8;
- let actual = store.data().get()[usize::try_from(i)?];
- assert_eq!(
- actual, expected,
- "buf[{i}] = {actual}, but should be {expected}"
- );
+ let expected = get_expected(iters);
+ let actual = store.data().get();
+ assert_eq!(actual, expected);
Ok(elapsed)
};
@@ -586,7 +640,8 @@ mod inc_random {
let linker = make_linker(&engine)?;
let mut builder = CodeBuilder::new(&engine);
- builder.wasm_binary_or_text(HOST_BUF_API_GUEST_WASM.as_bytes(), None)?;
+ let guest_wasm = host_buf_api_guest_wasm();
+ builder.wasm_binary_or_text(guest_wasm.as_bytes(), None)?;
// Allow the code we are building to use Wasmtime's unsafe intrinsics.
unsafe {
@@ -612,20 +667,14 @@ mod inc_random {
);
let instance = linker.instantiate(&mut store, &component)?;
let inc_random = instance.get_typed_func::<(u64,), ()>(&mut store, "inc-random")?;
- let i = get_random_index()?;
let start = Instant::now();
- for _ in 0..iters {
- inc_random.call(&mut store, (i,))?;
- }
+ inc_random.call(&mut store, (iters,))?;
let elapsed = start.elapsed();
- let expected = iters as u8;
- let actual = store.data().get()[usize::try_from(i)?];
- assert_eq!(
- actual, expected,
- "buf[{i}] = {actual}, but should be {expected}"
- );
+ let expected = get_expected(iters);
+ let actual = store.data().get();
+ assert_eq!(actual, expected);
Ok(elapsed)
};
@@ -637,7 +686,7 @@ mod inc_random {
static TAKE_AND_RETURN_INT_LIST_GUEST_WASM: &str = r#"
(component
(core module $m
- (memory (export "memory") 2)
+ (memory (export "memory") 3)
(func (export "realloc") (param i32 i32 i32 i32) (result i32)
;; Reserve the first two `u32`s of memory for the return-values buffer.
(i32.const 8)