javascriptnode.jsasynchronousbenchmark.js

Benchmark Asynchronous Code (Benchmark.js, Node.js)


I'd like to use the Benchmark.js module to test some asynchronous code written in node.js. Specifically, I want to fire ~10,000 requests to two servers (one written in node, one written in PHP), and track how long it takes for each server to complete all requests.

I was planning to write a simple node script to fire these requests using Benchmark, but I'm a little confused regarding how to use it with asynchronous code. Usually in node modules, there's some sort of a callback that you call when your async code is complete, or a Promise is returned from the function etc. But with Benchmark, from everything I'm reading in the docs, it doesn't seem to handle async at all.

Does anyone know what I should be doing or looking at? I can write the benchmark manually if need be; it just seems like a common enough use case that Benchmark or others would probably have already implemented it in their professional-grade testing libraries.

Thanks for any direction, ~ Nate


Solution

  • It's not very well documented, but here's a PoC:

    var Benchmark = require('benchmark');
    var suite     = new Benchmark.Suite();
    
    suite.add(new Benchmark('foo', {
      // a flag to indicate the benchmark is deferred
      defer : true,
    
      // benchmark test function
      fn : function(deferred) {
        setTimeout(function() {
          deferred.resolve();
        }, 200);
      }
    })).on('complete', function() {
      console.log(this[0].stats);
    }).run();
    

    Benchmark.js v2 slightly changes the syntax:

    var Benchmark = require('benchmark');
    var suite = new Benchmark.Suite;
    
    suite.add('foo', {
      defer: true,
      fn: function (deferred) {
        setTimeout(function() {
          deferred.resolve();
        }, 200);
      }
    }).on('complete', function () {
      console.log(this[0].stats)
    }).run()