Open In App

Node.js process.cpuUsage() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The process.cpuUsage() method is an inbuilt application programming interface of the Process module which is used to get the user, system CPU time usage of the current process. It is returned as an object with property user and system, values are in microseconds. Return values may differ from the actual time elapsed especially for multi-core CPUs.

Syntax: 

process.cpuUsage( previous_value )

Parameters: This method accepts a single parameter as mentioned above and described below:  

  • previous_value: It is an optional parameter, an object returned by the calling process.cpuUsage() previously. If it is passed then the difference is returned.

Return: This method returns an object on success, which contains properties like user and system, with some integer value that signifies time elapsed by the process, measured in microseconds. 

  • user: It is an integer that represents the time elapsed by user
  • system: It is an integer represents the time elapsed by system

Below examples illustrate the use of process.cpuUsage() method in Node.js:

Example 1:  

Javascript




// Allocating process module
const process = require('process');
  
// Calling process.cpuUsage() method
const usage = process.cpuUsage();
  
// Printing returned value
console.log(usage);


Output: 

{ user: 78000, system: 15000 }

Example 2: 

Javascript




// Allocating process module
const process = require('process');
  
// Calling process.cpuUsage() method
var usage = process.cpuUsage();
// Printing returned value
console.log("cpu usage before: ", usage);
  
// Current time
const now = Date.now();
  
// Loop to delay almost 100 milliseconds
while (Date.now() - now < 100);
  
// After using the cpu for nearly equal to 
// 100 milliseconds
// Calling process.cpuUsage() method
usage = process.cpuUsage(usage);
  
// Printing returned value
console.log("Cpu usage by this process: ", usage);


Output: 

cpu usage before:  { user: 62000, system: 15000 }
Cpu usage by this process:  { user: 109000, system: 0 }

Reference: https://nodejs.org/api/process.html#process_process_cpuusage_previousvalue
 



Last Updated : 12 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads