Skip to content

Instantly share code, notes, and snippets.

@brion brion/async-bench.js

Created Jan 12, 2019
Embed
What would you like to do?
Quick bench of a loop that does an async/await call on every iteration
"use strict";
class Bench {
constructor() {
this.x = 0;
this.iters = 1000000;
}
ms() {
return Date.now();
}
stepSync() {
return this.x = Math.random();
}
async stepAsync() {
return this.x = Math.random();
}
runSync() {
let start = this.ms();
for (let i = 0; i < this.iters; i++) {
this.stepSync();
}
let delta = this.ms() - start;
return delta;
}
async runAsync() {
let start = this.ms();
for (let i = 0; i < this.iters; i++) {
await this.stepAsync();
}
let delta = this.ms() - start;
return delta;
}
async run() {
console.log('warming up');
// warmup
this.runSync();
await this.runAsync();
let deltaSync = this.runSync();
console.log('sync ran in ' + deltaSync + ' ms')
let deltaAsync = await this.runAsync();
console.log('async ran in ' + deltaAsync + ' ms')
}
}
let bench = new Bench();
bench.run();
$ node async-bench.js
warming up
sync ran in 25 ms
async ran in 539 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.