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

前端 未结 2 593
感情败类
感情败类 2021-01-17 17:36

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 nod

2条回答
  •  [愿得一人]
    2021-01-17 18:08

    I came across this same issue when trying to test async functions. Here is an example of what I ended up using on Code Sand Box. Here is the link to the benchmark docs where it gives an example using the defer property.

    And here is the code I used in Node.js for anyone who comes along and wants to see deffered used with async/await. I hope someone finds this useful!

    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 });
    

提交回复
热议问题