Skip to content

Instantly share code, notes, and snippets.

@versusvoid
Last active April 16, 2019 19:07
Show Gist options
  • Save versusvoid/8ac4a2e489fdfaade2c69ba500d91821 to your computer and use it in GitHub Desktop.
Save versusvoid/8ac4a2e489fdfaade2c69ba500d91821 to your computer and use it in GitHub Desktop.
WebAssebly misaligned load test
clang -cc1 -emit-llvm-bc -triple=wasm32-unknown-unknown-wasm -std=c11 test.c
llc -filetype=obj test.bc -o test.o
wasm-ld --no-entry test.o -o test.wasm --export=aligned --export=misaligned --import-memory
wasm2wat test.wasm
const char a[] = {1,2,3,4,5,6,7,8};
int aligned(int i)
{
const int start = i % 3;
int value = ((int)a[start] << 0) + ((int)a[start + 1] << 8) + ((int)a[start + 2] << 16) + ((int)a[start + 3] << 24);
return i * value;
}
int misaligned(int i)
{
return i * (*(int*)(a + (i%3)));
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WASM aligned read test</title>
</head>
<body>
<script>
async function main() {
const resp = await fetch('test.wasm');
const wasm = await resp.arrayBuffer();
const memory = new WebAssembly.Memory({initial:10, maximum:100});
const module = await WebAssembly.instantiate(wasm, { env: { memory } });
const iterations = 100000000;
let start = new Date();
for (let i = 0; i < iterations; ++i) {
module.instance.exports.aligned(i);
}
console.log('aligned');
console.log(new Date() - start);
start = new Date();
for (let i = 0; i < iterations; ++i) {
module.instance.exports.misaligned(i);
}
console.log('misaligned');
console.log(new Date() - start);
};
main();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment