Hi Everyone,
After we prototype our code, the next priority comes in is to improve the performance. When it is about performance it is mostly about how much time it takes to execute the code. In this article , I will be explaining 2 ways to measure the performance of the Node.js code.
Scenario: We have a function apiCall()
which sometimes takes too much time and want to print time taken to execute the function so that we can debug the issue.
Using Console.time
console.time("timeTaken");
const reponse = await apicall();
console.timeEnd("timeTaken");
This will print the time taken to process the code between console.time and console.timeEnd. 'timeTaken' is just a label for the timer. You can use console.time and console.timeEnd in multiple time with "different labels".
console.timeLog
This method logs the current value of a timer that was previously started by calling console.time() to the console.
console.time("timeTaken");
await apiCall();
console.timeLog("timeTaken");
await apiCall();
console.timeLog("timeTaken");
console.timeLog("timeTaken");
...
Difference between console.timeEnd and console.timeLog is that, once console.timeEnd is called with a specific label it cannot be called again, if we want to log time multiple times within a code using the same label, we can use timeLog instead.
console.time has support for both browser and NodeJS. The accuracy is of milliseconds and if you want more accurate figures use the perflog library
Using perflog library (Node.js only)
perflog is a simple npm library which uses perf_hooks under the hood has several additional features
Install library :
npm i perflog
initialise
const perf = require("perflog")();
similar to console.time
// mark the point
perf("apiCall");
const response = await axios.get();
// mark again. between two perf() calls it logs the time in the console
perf("apiCall");
- log performance altogether
const perf = require("perflog")({inLineLog: false});
perf("apiCall");
const response = await axios.get();
perf("apiCall");
perf("db");
await db.create(data);
perf("db");
const summary = perf._summary;
console.log(summary);
output:
{
"apiCall": "1160.50",
"db": "1113.13"
}
perf._summary
object will have all the performance details. if inLineLog
option is false, it wont print the in line logs.
Options
const perf = require("perflog")({
enabled:true,
inLineLog:true,
round:2,
logPrefix:"PERF:"
});
Options | description |
enabled | To enable/disable library logging. If set to true, logging will be disabled. Default: true |
inLineLog | DEFAULT:true. if enabled, on the 2nd mark, it will console log the performance. |
round | DEFAULT:2, round off value. |
logPrefix | DEFAULT: 'PERF:' |
You can get more details from the doc here