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.
Further reading resources related to CPU profiling:
- https://netflixtechblog.com/node-js-in-flames-ddd073803aa4
- https://medium.com/voodoo-engineering/node-js-and-cpu-profiling-on-production-in-real-time-without-downtime-d6e62af173e2
- https://nodejs.org/api/inspector.html
- https://nodejs.org/en/learn/getting-started/profiling
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.
Get free courses inspired by the best practices used in open source.
About me:
Website: https://ramunarasinga.com/
Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/
Github: https://github.com/Ramu-Narasinga
Email: ramu.narasinga@gmail.com
Top comments (0)