本文介绍了基准异步代码(Benchmark.js,Node.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用模块测试一些写入的异步代码node.js中具体来说,我想向两台服务器发送~1,000个请求(一个用节点编写,一个用PHP编写),并跟踪每个服务器完成所有请求所需的时间。

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.

我打算编写一个简单的节点脚本来使用Benchmark来激发这些请求,但我对如何将它与异步代码一起使用感到困惑。通常在节点模块中,当你的异步代码完成时会调用某种回调,或者从函数中返回一个Promise等。但是使用Benchmark,从我在文档中读到的所有东西,它似乎都没有完全处理异步。

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.

有谁知道我应该做什么或看什么?如果需要,我可以手动编写基准;它似乎是一个常见的用例,Benchmark或其他人可能已经在他们的专业级测试库中实现了它。

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.

感谢任何方向,
~Nate

Thanks for any direction,~ Nate

推荐答案

这篇文章没有很好记录,但这里有一个PoC:

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略微更改语法:

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()

这篇关于基准异步代码(Benchmark.js,Node.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 00:13