简体   繁体   中英

How can measure response time for event-based NodeJs a

I have a scenario like this:

There is a NodeJS client application that calls an API service. Then the client then rises a listener to get a response.

Now I need to measure the response time from the API is called until the client receives the event.

Finally, I want to do performance testing for it.

//1) call API

//2) rise listener
context.events.myEvent().on('data', async event => {
      
      console.log("result"); 

 //3) here needs to measure Response time

});

Please help me to solve it.

You can use console.time() and console.timeEnd()

Call console.time() when you want to start the timer and console.timeEnd() to stop and print the elapsed time.

//1) call API
console.time("response time")

//2) rise listener
context.events.myEvent().on('data', async event => {
  //3) here needs to measure Response time
  console.timeEnd("response time")
});

documentation: console.time , console.timeEnd

If you need it in the form of a variable you have to manually get the timestamps and calculate it

//1) call API
let start = new Date().getTime()

//2) rise listener
context.events.myEvent().on('data', async event => {
  let end = new Date().getTime()

  //3) here needs to measure Response time
  let elapsedTime = end - start;
});

For anyone want to get time elapsed value instead of console output:

useprocess.hrtime() , below is my simpler approach:


context.events.myEvent().on('data', async event => {
    var startTime = process.hrtime();
    var elapsedSeconds = parseHrtimeToSeconds(process.hrtime(startTime));
    console.log('It takes ' + elapsedSeconds + 'seconds');
});

function parseHrtimeToSeconds(hrtime) {
    var seconds = (hrtime[0] + (hrtime[1] / 1e9)).toFixed(3);
    return seconds;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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