簡體   English   中英

基准異步代碼(Benchmark.js、Node.js)

[英]Benchmark Asynchronous Code (Benchmark.js, Node.js)

我想使用Benchmark.js模塊來測試一些用 node.js 編寫的異步代碼。 具體來說,我想向兩台服務器(一個用 node 編寫,一個用 PHP 編寫)發出大約 10,000 個請求,並跟蹤每個服務器完成所有請求所需的時間。

我打算編寫一個簡單的節點腳本來使用 Benchmark 來觸發這些請求,但我對如何將它與異步代碼一起使用感到有些困惑。 通常在節點模塊中,當你的異步代碼完成時,你會調用某種回調,或者從函數等返回一個 Promise。但是使用 Benchmark,從我在文檔中閱讀的所有內容來看,它似乎沒有完全處理異步。

有誰知道我應該做什么或看什么? 如果需要,我可以手動編寫基准測試; 它似乎是一個足夠常見的用例,Benchmark 或其他公司可能已經在他們的專業級測試庫中實現了它。

感謝您的任何指導,〜內特

它沒有很好的文檔記錄,但這里有一個 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()

我在嘗試測試異步函數時遇到了同樣的問題。 這是我最終在Code Sand Box上使用的示例。 這是基准文檔的鏈接,其中給出了使用defer屬性的示例。

這是我在 Node.js 中使用的代碼,供任何想看到defferedasync/await deffered使用的人使用。 我希望有人覺得這很有用!

const Benchmark = require('benchmark');
const suite = new Benchmark.Suite();
const promiseCount = 10;
const setupArray = Array.from(Array(promiseCount)).map((_, i) => i);

const sleep = (ms = 500) =>
  new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, ms);
  });

const asyncFunction = async (name, index) => {
  await sleep(100);
  return `${name}_${index}`;
};

suite
  .add("Promise.all", {
    defer: true,
    fn: async function(deferred) {
      const promiseArray = setupArray.map(asyncFunction);
      await Promise.all(promiseArray);
      deferred.resolve();
    }
  })
  .add("For loop", {
    defer: true,
    fn: async function(deferred) {
      const final = [];

      for (let i = 0; i < promiseCount; i++) {
        const data = await asyncFunction(setupArray[i], i);
        final.push(data);
      }
      deferred.resolve();
    }
  })
  .on("cycle", function(event) {
    console.log(String(event.target));
  })
  .on("complete", function() {
    console.log("Fastest is " + this.filter("fastest").map("name"));
  })
  .run({ async: true });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM