0.1.0 • Published 11 months ago

als-cpu-usage v0.1.0

Weekly downloads
-
License
ISC
Repository
-
Last release
11 months ago

als-cpu-usage

als-cpu-usage is a simple utility module that helps you calculate the CPU usage in your Node.js application. The module exports three functions: getCpu, calcCpuPerc, and cpuUsage.

Methods

import methods

const {getCpu,calcCpuPerc,cpuUsage} = require('als-cpu-usage');

getCpu

The getCpu function retrieves the total CPU time and the idle CPU time. The function does not accept any parameters and returns an object with two properties:

  • total: The total time that the CPU has spent in different modes (user, nice, sys, idle, irq).
  • idle: The total time that the CPU has spent in idle mode.

Example:

let cpuTimes = getCpu();
console.log(cpuTimes); // Output: { total: 123456, idle: 78910 }

calcCpuPerc

The calcCpuPerc function calculates the percentage of CPU usage. It accepts two parameters, start and end, which should be objects returned by the getCpu function. The function calculates the difference between the total and idle times and returns the CPU usage as a decimal number.

Example:

let start = getCpu();
// CPU-intensive operation goes here...
let end = getCpu();
console.log(calcCpuPerc(start, end)); // Output: 0.15 (this means 15% CPU usage)

cpuUsage

The cpuUsage function uses the two previous functions to calculate the CPU usage over a one-second period. The function does not accept any parameters and returns a Promise that resolves to the CPU usage as a decimal number.

Example:

// Get CPU usage as a Promise
cpuUsage().then(perc => console.log(perc));

// Or with async/await
(async function() {
   console.log(await cpuUsage());
})();

Example Usage

Here is an example that sets up a simple CPU monitor. It calculates the CPU usage every second and prints it to the console:

let start = getCpu();
setInterval(() => {
   let end = getCpu();
   const perc = calcCpuPerc(start, end);
   start = end;
   console.log(perc);
}, 1000);

In this example, getCpu is first called to get the initial CPU times. Then, every second, getCpu is called again to get the new CPU times, and calcCpuPerc is used to calculate the CPU usage during that interval. The start variable is then updated to the new CPU times for the next interval.