Skip to main content

Measuring Performance of Node.js Program Using Performance Hook Module

Node.js has provided tools for measuring or benchmarking your application performance by marking certain blocks of codes and capturing the duration of the executions. For example, you have a program example.js that run two functions, generate a random string, and make a request to facebook.com, as follows.

const https = require('https');
const debuglog = require('util').debuglog('example');

// 1) generate 100 digits random string
let randomStr = '';
let allowedChars = 'abcdefghijklmnopqrstuvwxyz0123456789';
for (let i=0; i<100; i++) {
  randomStr += allowedChars.charAt(Math.floor(Math.random() * allowedChars.length));
}
debuglog('Random String:', randomStr);

// 2) make a request to facebook.com
let request = https.request({
  protocol: 'https:',
  hostname: 'facebook.com',
  method: 'GET',
  path: '/'
}, (res)=>{
  if (res.statusCode) {
    debuglog('Request Status Code:', res.statusCode);
  }
});
request.on('error',(err)=>{
  debuglog('Request Error:', err);
})
request.end();

Run the program with this command.

NODE_DEBUG=example node example.js

Then, you can utilize perf_hook module by marking specified starting points of measurement and observing the result. The final code will be as follows.

const https = require('https');
const debuglog = require('util').debuglog('performance');
const {performance, PerformanceObserver} = require('perf_hooks');

// create observer
const perfObs = new PerformanceObserver((list) => {
  const entries = list.getEntries();
  entries.forEach( entry => {
    debuglog('\x1b[32m%s\x1b[0m', `Measurement - ${entry.name}: ${entry.duration}`);
  });
  performance.clearMarks();
});
perfObs.observe({entryTypes: ['measure'], buffered: true});

// 1) generate 100 digits random string
performance.mark('begin random string');

let randomStr = '';
let allowedChars = 'abcdefghijklmnopqrstuvwxyz0123456789';
for (let i=0; i<100; i++) {
  randomStr += allowedChars.charAt(Math.floor(Math.random() * allowedChars.length));
}

performance.mark('complete random string');
debuglog('Random String:', randomStr);

// 2) make a request to facebook.com
performance.mark('begin http request');

let request = https.request({
  protocol: 'https:',
  hostname: 'facebook.com',
  method: 'GET',
  path: '/'
}, (res)=>{
  performance.mark('complete http request');
  
  performance.measure('random string', 'begin random string', 'complete random string');
  performance.measure('http request', 'begin http request', 'complete http request'); 
  performance.measure('start to end', 'begin random string', 'complete http request');

  if (res.statusCode) {
    debuglog('Request Status Code:', res.statusCode);
  }
});
request.on('error',(err)=>{
  debuglog('Request Error:', err);
})
request.end();

Comments