Skip to content
Related Articles

Related Articles

Node.js | process.cpuUsage() Method
  • Last Updated : 02 Mar, 2020

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 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:




// 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:




// 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 miliseconds
while (Date.now() - now < 100);
  
// After using the cpu for nearly equal to 
// 100 miliseconds
// 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

My Personal Notes arrow_drop_up
Recommended Articles
Page :