本文介绍了如何测量Node.js中异步函数的执行时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get the execution/response time of an asynchronous function that executes inside a node-fetch operation, like the following

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

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

I Used the library perf_hooks like this, but the execution time shows before

const hrtime = require ('perf_hooks').performance.now ;
var start = hrtime ();
   getEditedData();
var end   = hrtime ();
console.log (end - start);

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

I found the async_hooks library https://nodejs.org/api/perf_hooks.html#perf_hooks_measuring_the_duration_of_async_operations , but I can´t understand how it works. I am a basic in javascript/nodejs

推荐答案

您可以简单地存储 Date.now() ,然后在Promise解析(或拒绝)并减去以找出差异时检查Date.now().例如:

You could simply store Date.now() in some variable and then check Date.now() when your Promise resolves (or rejects) and subtract to find the difference. For example:

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

注意:通过使用await/async,您可以编写实现相同功能并看起来是同步的代码,因为那只是基于Promises构建的语法糖".例如:

Note: You could write code that achieves the same thing and appears to be synchronous by using await/async since that is just "syntactic sugar" built on top of Promises. For example:

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.`);
})();

这篇关于如何测量Node.js中异步函数的执行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:37