如何测量nodejs中异步函数的执行时间?

Kev*_*ezz 5 javascript performance measure node.js async-await

我正在尝试获取在节点获取操作中执行的异步函数的执行/响应时间,如下所示

async function getEditedData() {      
       var a = await fetch(`https://api.example.com/resorce_example`);
       var b = await a.json();
       // Some aditional treatment of the object obtained (b)
       console.log("End of the asynchronous function")
}
Run Code Online (Sandbox Code Playgroud)

我像这样使用了库 perf_hooks,但执行时间显示之前

const hrtime = require ('perf_hooks').performance.now ;
var start = hrtime ();
   getEditedData();
var end   = hrtime ();
console.log (end - start);
Run Code Online (Sandbox Code Playgroud)

我找到了 async_hooks 库https://nodejs.org/api/perf_hooks.html#perf_hooks_measuring_the_duration_of_async_operations,但我不明白它是如何工作的。我是 javascript/nodejs 的基础

Tom*_* O. 3

您可以简单地存储Date.now()在一些变量中,然后检查Date.now()您的 Promise 何时解决(或拒绝)并减去以找出差异。例如:

const simulateSomeAsyncFunction = new Promise((resolve, reject) => {
  console.log('Initiating some async process, please wait...')
  const startTime = Date.now();

  setTimeout(() => {
    resolve(Date.now() - startTime);
  }, 3000);
});

simulateSomeAsyncFunction.then(msElapsed => {
  console.log(`Async function took ${msElapsed / 1000} seconds to complete.`);
});
Run Code Online (Sandbox Code Playgroud)

注意await:您可以编写实现相同功能的代码,并且通过使用/看起来是同步的,async因为这只是构建在 Promise 之上的“语法糖”。例如:

const simulateSomeAsyncFunction = () => {
  console.log('Initiating some async process, please wait...');

  return new Promise((resolve, reject) => {
    setTimeout(resolve, 3000);
  });
};

// Await is required to be called within an async function so we have to wrap the calling code in an async IIFE
(async() => {
  const startTime = Date.now();

  await simulateSomeAsyncFunction();

  const msElapsed = Date.now() - startTime;

  console.log(`Async function took ${msElapsed / 1000} seconds to complete.`);
})();
Run Code Online (Sandbox Code Playgroud)