Skip to content

Instantly share code, notes, and snippets.

@bvibber
Created January 12, 2019 03:21
Show Gist options
  • Save bvibber/a100b22145dfee4a8bf68e203ce1923c to your computer and use it in GitHub Desktop.
Save bvibber/a100b22145dfee4a8bf68e203ce1923c to your computer and use it in GitHub Desktop.
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