Skip to content

Instantly share code, notes, and snippets.

@bojand
Last active June 29, 2018 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bojand/942a641436329e0256866a434e9f36b7 to your computer and use it in GitHub Desktop.
Save bojand/942a641436329e0256866a434e9f36b7 to your computer and use it in GitHub Desktop.
Simple WebAssembly fibonacci performance test

Simple, quick performance demo / test comparing JavaScript and WebAssembly. Uses fibonacci (n = 40) with 31 runs.

Convert fib.wat to wasm using wat2wasm tool and download as fib.wasm.

Use Node.js 10.

Run:

node index.js

Sample result:

[WASM] total: 21083.41 ms average: 680.11 ms
[JS] total: 38589.46 ms average: 1244.82 ms
(module
(export "fib" (func $fib))
(func $fib (param $n i32) (result i32)
(if
(i32.lt_s
(get_local $n)
(i32.const 2)
)
(return
(i32.const 1)
)
)
(return
(i32.add
(call $fib
(i32.sub
(get_local $n)
(i32.const 2)
)
)
(call $fib
(i32.sub
(get_local $n)
(i32.const 1)
)
)
)
)
)
)
const fs = require('fs')
const util = require('util')
const path = require('path')
const readFile = util.promisify(fs.readFile)
const { PerformanceObserver, performance } = require('perf_hooks')
async function main () {
const buf = await readFile(path.resolve(__dirname, './fib.wasm'))
const res = await WebAssembly.instantiate(new Uint8Array(buf.buffer))
const { fib } = res.instance.exports
bench('WASM', fib)
bench('JS', fibonacci)
}
function bench (label, fn) {
const N_ITERS = 30
const observations = []
const obs = new PerformanceObserver(list => {
const entries = list.getEntries()
observations.push(...entries)
performance.clearMarks()
})
obs.observe({ entryTypes: ['measure'] })
for (let i = 0; i <= N_ITERS; ++i) {
performance.mark('A')
fn(40)
performance.mark('B')
performance.measure('A to B', 'A', 'B')
}
const total = observations.reduce((total, e) => total + e.duration, 0)
const avg = total / observations.length
const totalFx = Number.parseFloat(total).toFixed(2)
const avgFx = Number.parseFloat(avg).toFixed(2)
console.log(`[${label}] total: ${totalFx} ms average: ${avgFx} ms`)
}
function fibonacci (num) {
if (num <= 1) return 1
return fibonacci(num - 1) + fibonacci(num - 2)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment