简体   繁体   English

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

[英]How to measure the execution time of an asynchronous function in nodejs?

I'm trying to get the execution/response time of an asynchronous function that executes inside a node-fetch operation, like the following我正在尝试获取在节点获取操作中执行的异步 function 的执行/响应时间,如下所示

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

I Used the library perf_hooks like this, but the execution time shows before我像这样使用了库 perf_hooks,但执行时间显示在之前

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

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.我找到了 async_hooks 库https://nodejs.org/api/perf_hooks.html#perf_hooks_measuring_the_duration_of_async_operations ,但我不明白它是如何工作的。 I am a basic in javascript/nodejs我是 javascript/nodejs 的基础

If you expect to set the end after getEditedData() is completed, you actually need to await getEditedData() .如果您希望在getEditedData()完成后设置end ,您实际上需要await getEditedData() Otherwise, you'll go right past it while it executes... asynchrnously.否则,当它执行时,您将在 go 旁边通过它......异步。

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.您可以简单地将Date.now()存储在某个变量中,然后在您的 Promise 解析(或拒绝)时检查Date.now() ) 并减去以找出差异。 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.`); });

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.注意:您可以编写代码来实现相同的目标,并且使用await / async看起来是同步的,因为这只是构建在 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.`); })();

Starting with a simple async function -从一个简单的异步 function 开始 -

 const fakeAsync = async (value) => { const delay = 2000 + Math.random() * 3000 // 2 - 5 seconds return new Promise(r => setTimeout(r, delay, value)) } fakeAsync("foo").then(console.log) console.log("please wait...") // "please wait..." // "foo"

We could write a generic function, timeit .我们可以写一个通用的 function, timeit This is a higher-order function that accepts a function as input and returns a new function as output.这是一个高阶 function,它接受一个 function 作为输入,并返回一个新的 function 作为 Z77A94F14Z3F138E62281F698。 The new function operates like a decorated version of the original -新的 function 运行起来就像原始版本的装饰版本 -

const timeit = (func = identity) => async (...args) => {
  const t = Date.now()
  const result = await func(...args)
  return { duration: Date.now() - t, result }
}

// decorate the original
const timedFakeAsync = timeit(fakeAsync)

// call the decorated function
timedFakeAsync("hello").then(console.log)
timedFakeAsync("earth").then(console.log)

// { duration: 3614, result: "earth" }
// { duration: 4757, result: "hello" }

The timed version of our function returns an object, { duration, result } , that reports the runtime of our async function and the result.我们的 function 的定时版本返回一个 object, { duration, result } ,它报告我们的异步 function 的运行时间和结果。

Expand the snippet below to verify the results in your own browser -展开下面的代码片段以在您自己的浏览器中验证结果 -

 const identity = x => x const timeit = (func = identity) => async (...args) => { const t = Date.now() const result = await func(...args) return { duration: Date.now() - t, result } } const fakeAsync = async (value) => { const delay = 2000 + Math.random() * 3000 // 2 - 5 seconds return new Promise(r => setTimeout(r, delay, value)) } const timedFakeAsync = timeit(fakeAsync) timedFakeAsync("hello").then(console.log) timedFakeAsync("earth").then(console.log) console.log("please wait...") // "please wait..." // { duration: 3614, result: "earth" } // { duration: 4757, result: "hello" }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM