skip to Main Content

Given an arbitrary async function in Node.js, is there any way to properly measure the CPU usage of that function, including all of its async microtasks?

I thought async_hooks was the way to do this, but I’m not sure how and it’s now marked as deprecated. The deprecation notice links to AsyncLocalStorage for context tracking (which we use already) and this new diagnostics_channel API, which seems unhelpful and irrelevant to this (although the documentation for that is so unclear that I could be wrong).

Note that this is for continuous monitoring of a large system, so using the debugger is not relevant. At the moment we’ve just got the overall CPU usage of the process, but it would be more much helpful if we could break this down to get metrics for different parts of the system.

2

Answers


  1. You could potentially run the functions in node child processes. And then find the process PID and then ask the system for information about that PID.

    The process of getting information from the PID varies from system to system depending on the OS and bash commands available, however I was able to find this module to simplify the process.

    yarn add pidusage
    
    npm install pidusage
    
    const { spawn } = require('child_process');
    const pidusage = require('pidusage')
    
    const child = spawn('node', ['childScript.js'], {
        detached: true, // Allow the child process to continue running independently of the parent
        stdio: 'ignore' // Ignore the child process output
    });
    
    const { pid } = child;
    
    pidusage(pid, (err, stats) => {
      console.log({
        cpu: stats.cpu,
        mem: stats.memory
      })
    });
    
    // Or in an asynchronous function
    
    const { cpu, memory } = await pidusage(pid);
    console.log({ cpu, memory });
    
    Login or Signup to reply.
  2. You might consider using a Flame Graph for that. It would give you more context than watching a single async function.

    https://nodejs.org/en/learn/diagnostics/flame-graphs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search