Lessons from open-source: CPU profiling in NodeJs.

Lessons from open-source: CPU profiling in NodeJs.

This lesson is picked from Nextjs Source code. In this article, you will learn what CPU profiling means, how Next.js source code uses it.

CPU profiling:

CPU profiling in Node.js refers to the process of analysing the usage of the CPU by the application code. It involves identifying which parts of the code are consuming the most CPU resources, how often they are being executed, and how long they take to execute.

Node.js provides built-in tools for CPU profiling, such as the — prof command-line option, which allows you to generate a CPU profile file. This file contains information about the execution of JavaScript functions, including how much time each function takes to execute and how many times it is called.

Practice the exercises based on documentation to become an expert in Next.js.

How Next.js uses CPU profiling?

You can find the code related to CPU profiling used in Next.js source code at cpu-profile.ts. The code inside reveals that this profiling is saved to a local file depending on an env variable as shown below.

const privateCpuProfileName = process.env.__NEXT_PRIVATE_CPU_PROFILE
const isCpuProfileEnabled = process.env.NEXT_CPU_PROF || privateCpuProfileName

if (isCpuProfileEnabled) {
  const { Session } = require('inspector') as typeof import('inspector')
  const fs = require('fs')

  const session = new Session()
  session.connect()

  session.post('Profiler.enable')
  session.post('Profiler.start')

  function saveProfile() {
    session.post('Profiler.stop', (error, param) => {
      if (error) {
        console.error('Cannot generate CPU profiling:', error)
        return
      }

      // Write profile to disk
      const filename = `${
        privateCpuProfileName || 'CPU.main'
      }.${Date.now()}.cpuprofile`
      fs.writeFileSync(`./${filename}`, JSON.stringify(param.profile))
      process.exit(0)
    })
  }
  process.on('SIGINT', saveProfile)
  process.on('SIGTERM', saveProfile)
  process.on('exit', saveProfile)
}

This file is imported in 3 other files related to CLI.

Conclusion:

As I keep reading more and more open source code, I find myself spiralling around the concepts such as observability, instrumentation, memory leaks, performance, using the right data structure/algorithm.

In this article, I have written about CPU profiling for performance monitoring in NodeJs and how Nextjs uses CPU profiling in the CLI related files.