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.
CodePudding user response:
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;
});
CodePudding user response:
For anyone want to get time elapsed value instead of console output :
use process.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;
}