DEV Community

Cover image for Code Profiling 101: Tools and Techniques to Boost Performance – Part 1
Rijul Rajesh
Rijul Rajesh

Posted on

Code Profiling 101: Tools and Techniques to Boost Performance – Part 1

There can be situations where you deal with performance issues in your code. So identifying the root cause is essential.

For such problems, developers often use a tool called a profiler.

Let's see what profilers do and set one up real quick.

What is a profiler?

A profiler tells you exactly where your program spends its time when it runs.

Instead of guessing "Why is my code slow?", the profiler records every function and shows you a precise report.

How does a profiler work?

  1. Every 1 millisecond, the profiler pauses your program for a split second.
  2. It looks at the call stack for that exact moment (which functions are currently running or waiting).
  3. It records that snapshot.
  4. It repeats this thousands of times.
  5. At the end, it adds up all the snapshots.

When you run the profiler, you can get a .cpuprofile file generated.

Simple Demo

Enough with the theory, let's try something out.

Create a demo.js file:

function fast() {
  return Math.sqrt(42) * 2;
}

function wasteCpu(ms) {
  const start = Date.now();
  while (Date.now() - start < ms) {
    Math.random() * Math.random();
  }
}

function slowJson() {
  for (let i = 0; i < 50_000; i++) {
    JSON.parse('{"a":1,"b":2,"c":[1,2,3,4,5,6,7,8,9,0]}');
  }
}

function slowerRegex() {
  const badRegex = /^(a+)+$/;
  for (let i = 0; i < 200; i++) {
    "aaaaaaaaaaaaaaaaaaaa".match(badRegex);
  }
}

function main() {
  console.log("Starting demo… (this will take ~15 seconds)");

  for (let i = 0; i < 20; i++) {
    fast();
    wasteCpu(100);
    slowJson();
  }

  slowerRegex();

  console.log("Done! Check the generated .cpuprofile file");
}

main();
Enter fullscreen mode Exit fullscreen mode

Now let's run this file using the CPU profiler:

node --cpu-prof demo.js
Enter fullscreen mode Exit fullscreen mode

Once you run this, you can see this:

node --cpu-prof demo.js
Starting demo… (this will take ~15 seconds)
Done! Check the generated .cpuprofile file
Enter fullscreen mode Exit fullscreen mode

You can see a file like this:

CPU.20251209.015502.282904.0.001.cpuprofile
Enter fullscreen mode Exit fullscreen mode

Now let's unbox this and see what is inside.

What can you see in a .cpuprofile?

  • To check, first go to chrome://inspect
  • Click "Open dedicated DevTools for Node"

  • Switch to the Performance tab

  • Upload the .cpuprofile file

  • You can see the following after uploading

Now, this shows a lot of information. We will understand more in detail in the next article.

Here's a bonus for ya, if you are keen on improving your workflow, Let me suggest you a platform, It’s free, open-source, and built with developers in mind.

👉 Explore the tools: FreeDevTools
👉 Star the repo: freedevtools

Top comments (0)