process.cpuUsage() Method in Node.js

The process.cpuUsage() method returns CPU time consumption information for the current Node.js process. It provides data about user and system CPU time in microseconds (10^-6 seconds).

Syntax

process.cpuUsage([previousValue])

Parameters

  • previousValue - Optional parameter. A previous return value from calling process.cpuUsage() to calculate the difference in CPU usage.

Return Value

Returns an object with two properties:

  • user - CPU time spent in user code (microseconds)

  • system - CPU time spent in system calls (microseconds)

Example: Basic CPU Usage

// Getting the current CPU usage
const usage = process.cpuUsage();

// Printing the CPU usage values
console.log("CPU Usage:", usage);
console.log("User time:", usage.user, "microseconds");
console.log("System time:", usage.system, "microseconds");
CPU Usage: { user: 352914, system: 19826 }
User time: 352914 microseconds
System time: 19826 microseconds

Example: Measuring CPU Usage Difference

// Get initial CPU usage
const startUsage = process.cpuUsage();
console.log("CPU usage before:", startUsage);

// Simulate CPU-intensive work
const now = Date.now();
while (Date.now() - now < 100) {
    // Busy loop for 100ms
}

// Calculate CPU usage difference
const diffUsage = process.cpuUsage(startUsage);
console.log("CPU usage during operation:", diffUsage);
CPU usage before: { user: 357675, system: 32150 }
CPU usage during operation: { user: 93760, system: 95 }

Key Points

  • Values are returned in microseconds (1/1,000,000 seconds)

  • When previousValue is provided, returns the difference in CPU usage

  • Values may exceed actual elapsed time on multi-core systems

  • Useful for performance monitoring and profiling

Common Use Cases

// Performance monitoring function
function measureCPUUsage(callback) {
    const start = process.cpuUsage();
    
    // Execute the callback
    callback();
    
    const usage = process.cpuUsage(start);
    console.log(`Function consumed: ${usage.user + usage.system} microseconds`);
    return usage;
}

// Example usage
measureCPUUsage(() => {
    // Some computation
    let sum = 0;
    for (let i = 0; i < 1000000; i++) {
        sum += i;
    }
});
Function consumed: 15420 microseconds

Conclusion

The process.cpuUsage() method is essential for performance monitoring in Node.js applications. Use it to measure CPU consumption and optimize resource-intensive operations.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements