Performance profiling in node.js

Small tips to know how our node.js apps perform, how to detect bottle-necks and performance opportunities.

Performance is super important, and we are always mentioning how many requests can x framework handle per second or how many operations can this library achive. But before looking into that, there might be lots of things wrong in our apps.

This post is about localizing those things in the most simple way.

Measuring time

With console.time you can measure the executing time between point A and B.

console.time('timestampId')
console.timeEnd('timestampId')

If you need even more detail of the time consumed. You could use process.hrtime, which returns nanoseconds.

const timeStart = process.hrtime()
process.hrtime(timeStart)

And if you need to know the amount of time the app has been running, you can use process.uptime() which returns that with fractions of a second.

process.uptime()

Measuring cpu

With process.cpuUsage you can get the amount of cpu the app is using. The function returns a reference that you can later pass to the same function to know the variant of cpu usage between those points.

That way you can know how much cpu has been using by a certain process.

const startCpuUsage = process.cpuUsage()
console.log(process.cpuUsage(startCpuUsage))

Measuring memory

With process.memoryUsage you can get the amount of memory tha app is using at a given moment. There is no way to calculate the amount used by a portion of the app, but several calls could give you that.

process.memoryUsage()

Measuring disk

I'm not sure about this to be honest. I haven't found a tool to easily do this, like we are can do on the others. Because there are still places to fix and improve, as well tools to come in node.js.