process.cpuUsage() Method in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

The process.argv() method is used for getting the user and its cpu usage for the current running process. The data is returned in an object with the properties user and system. The values obtained are in microseconds,i.e.10^-6 seconds. The values returned may be greater than the actual elapsed time if multiple cores are performing work for the running process.

Syntax

process.cpuUsage([previousValue])

Parameters

The method only accepts a single parameter which is defined below −

  • previousValue – This is an optional parameter. This is the previous return value by calling the process.cpuUsage() method.

Example

Create a file with name – cpuUsage.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −

node cpuUsage.js

cpuUsage.js

 Live Demo

// Node.js program to demonstrate the use of process.argv

// Importing the process module
const process = require('process');

// Getting the cpu usage details by calling the below method
const usage = process.cpuUsage();

// Printing the cpu usage values
console.log(usage);

Output

admin@root:~/node/test$ node cpuUsage.js
{ user: 352914, system: 19826 }

Example

Let's take a look at one more example.

 Live Demo

// Node.js program to demonstrate the use of process.argv

// Importing the process module
const process = require('process');

// Getting the cpu usage details by calling the below method
var usage = process.cpuUsage();
// Printing the cpu usage values
console.log("cpu usage before: ", usage);

// Printing the current time stamp
const now = Date.now();

// Looping to delay the process for 100 milliseconds
while (Date.now() - now < 100);

// After using the cpu for nearly 100ms
// calling the process.cpuUsage() method again...
usage = process.cpuUsage(usage);

// Printing the new cpu usage values
console.log("Cpu usage by this process: ", usage);

Output

admin@root:~/node/test$ node cpuUsage.js
cpu usage before: { user: 357675, system: 32150 }
Cpu usage by this process: { user: 93760, system: 95 }
raja
Published on 20-May-2021 13:16:40
Advertisements