pidusage

repository·main·Indexed 19 days ago

https://github.com/soyuka/pidusage

A cross-platform library for retrieving CPU percentage and memory usage of specific Process IDs (PIDs) without C-bindings. Supports single PIDs or arrays of PIDs across Unix-like systems and Windows. Version 3.0.1 provides statistics including cpu, memory, ppid, pid, ctime, elapsed, and timestamp.

Tokens
1.4K
Snippets
8
Records
9
Agent score
19%

What's inside pidusage

  1. Configure pidusage options

    main

    You can pass an options object to pidusage() to customize behavior. These options override the corresponding environment variables.

    OptionTypeEnv VarDefaultDescription
    usePsbooleanPIDUSAGE_USE_PSfalseIf true, uses the ps command instead of parsing /proc files.
    maxagenumberPIDUSAGE_MAXAGE60000Maximum age of a process in history (ms).

    Additionally, setting the environment variable PIDUSAGE_SILENT=1 will suppress all console messages triggered by the library.

    // Use 'ps' instead of proc files
    pidusage(pid, { usePs: true })
  2. Implement a non-overlapping polling interval

    main

    When monitoring process statistics repeatedly, avoid using setInterval as asynchronous processing might overlap. Instead, use recursive setTimeout calls to ensure the previous measurement is complete before scheduling the next one.

    Async/Await Pattern:

    const interval = async (time) => {
      setTimeout(async () => {
        await compute()
        interval(time)
      }, time)
    }
    const compute = async () => {
      const stats = await pidusage(process.pid)
      // do something with stats
    }
    
    const interval = async (time) => {
      setTimeout(async () => {
        await compute()
        interval(time)
      }, time)
    }
    
    interval(1000) // Run every 1000ms
  3. Run the server.js example

    main

    The server.js example demonstrates how to use pidusage in a server environment. To test the performance or behavior of this example, you can use an HTTP benchmark tool like wrk against localhost:8020 after starting the server.

    # Start the server, run the tests on localhost:8020
  4. Get process CPU and memory usage with pidusage()

    main

    The pidusage function retrieves cross-platform CPU percentage and memory usage for one or more PIDs.

    It supports:

    • A single PID (Number or String).
    • An array of PIDs (Array of Numbers or Strings).

    If a callback is provided, it follows the Node.js error-first callback pattern. If no callback is provided, it returns a Promise that resolves to the statistics object.

    var pidusage = require('pidusage')
    
    // Using a callback
    pidusage(process.pid, function (err, stats) {
      console.log(stats)
    })
    
    // Using Promises/async/await
    const stats = await pidusage(process.pid)
    console.log(stats)
    
    // Using multiple PIDs
    pidusage([727, 1234], function (err, stats) {
      // stats is an object keyed by PID
      console.log(stats[727])
    })
  5. Clear in-memory metrics with pidusage.clear()

    main

    The pidusage.clear() method deletes all in-memory metrics and clears the event loop. This is useful if you need to reset the internal history. It is generally not required before exiting the process, as the internal interval does not prevent the event loop from exiting.

    const pidusage = require('pidusage')
    
    // Clear all cached metrics
    pidusage.clear()
  6. Understand the pidusage stats object format

    main

    The statistics object returned by pidusage contains the following fields:

    FieldTypeDescription
    cpuNumberPercentage (from 0 to 100 * vcore)
    memoryNumberMemory usage in bytes
    ppidNumberParent Process ID
    pidNumberProcess ID
    ctimeNumberMilliseconds of user + system time
    elapsedNumberMilliseconds since the start of the process
    timestampNumberMilliseconds since epoch
    // Example output for a single PID
    {
      cpu: 10.0,
      memory: 357306368,
      ppid: 312,
      pid: 727,
      ctime: 867000,
      elapsed: 6650000,
      timestamp: 864000000
    }
    
    // Example output for multiple PIDs
    {
      727: { ... },
      1234: { ... }
    }
  7. Check platform compatibility

    main

    The availability of specific metrics depends on the operating system:

    MetricLinuxmacOSWindowsAlpineFreeBSD/NetBSD/SunOS/AIX
    cpuℹ️
    memory
    pid
    ctime
    elapsed
    timestamp

    Legend: ✅ Working, ℹ️ Not Accurate, ❓ Should Work, ❌ Not Working

  8. Clear pidusage history with pidusage.clear()

    main

    Use pidusage.clear() to clear the internal history/cache of process statistics. This is useful if you want to force the library to fetch fresh data instead of using cached values.

    const pidusage = require('pidusage');
    
    // Clear the history/cache
    pidusage.clear();