The systemUsage
function monitors system CPU usage and memory usage over time, calculating and returning the average percentage usage in an object format. It measures CPU usage at regular intervals, calculates the average CPU usage, and stores memory usage data in an object.
npm run import -- "system usage report"
const os = require('os')
const reportCPU = []
const reportMem = []
//Create function to get CPU information
function cpuAverage() {
//Initialise sum of idle and time of cores and fetch CPU info
var totalIdle = 0, totalTick = 0;
var cpus = os.cpus();
//Loop through CPU cores
for(var i = 0, len = cpus.length; i < len; i++) {
//Select CPU core
var cpu = cpus[i];
//Total up the time in the cores tick
for(type in cpu.times) {
totalTick += cpu.times[type];
}
//Total up the idle time of the core
totalIdle += cpu.times.idle;
}
//Return the average Idle and Tick times
return {idle: totalIdle / cpus.length, total: totalTick / cpus.length};
}
async function systemUsage() {
var startMeasure = cpuAverage();
reportMem.unshift(Math.round(100 * (os.totalmem() - os.freemem()) / os.totalmem()))
await new Promise(resolve => setTimeout(resolve, 1000))
var endMeasure = cpuAverage();
//Calculate the difference in idle and total time between the measures
var idleDifference = endMeasure.idle - startMeasure.idle;
var totalDifference = endMeasure.total - startMeasure.total;
//Calculate the average percentage CPU usage
var percentageCPU = 100 - ~~(100 * idleDifference / totalDifference);
reportCPU.unshift(percentageCPU)
if(reportMem.length > 30 || reportCPU.length > 30) {
reportMem.pop()
reportCPU.pop()
}
return {
memory: reportMem,
cpus: reportCPU
}
}
module.exports = systemUsage
/**
* Requires the os module for system information.
* @module systemUsage
*/
const os = require('os');
/**
* System usage class with methods for CPU and memory usage.
* @class SystemUsage
*/
class SystemUsage {
/**
* Calculates the average idle and tick times for the CPU.
* @returns {Object} An object with average idle and total times.
*/
static async getCPUInfo() {
const cpus = os.cpus();
let totalIdle = 0, totalTick = 0;
for (const cpu of cpus) {
for (const type in cpu.times) {
totalTick += cpu.times[type];
}
totalIdle += cpu.times.idle;
}
return {
idle: totalIdle / cpus.length,
total: totalTick / cpus.length
};
}
/**
* Calculates the system usage (CPU and memory) over time.
* @returns {Object} An object with memory and CPU usage arrays.
*/
static async systemUsage() {
// Initialize arrays for memory and CPU usage
const reportMem = [];
const reportCPU = [];
// Get initial CPU info
const startMeasure = await SystemUsage.getCPUInfo();
// Get initial memory usage
const memUsage = Math.round(100 * (os.totalmem() - os.freemem()) / os.totalmem());
reportMem.unshift(memUsage);
// Wait 1 second to measure CPU usage
await new Promise(resolve => setTimeout(resolve, 1000));
// Get final CPU info
const endMeasure = await SystemUsage.getCPUInfo();
// Calculate CPU usage
const idleDifference = endMeasure.idle - startMeasure.idle;
const totalDifference = endMeasure.total - startMeasure.total;
const percentageCPU = 100 - ~~(100 * idleDifference / totalDifference);
reportCPU.unshift(percentageCPU);
// Ensure arrays are not too large
if (reportMem.length > 30 || reportCPU.length > 30) {
reportMem.pop();
reportCPU.pop();
}
return {
memory: reportMem,
cpus: reportCPU
};
}
}
module.exports = SystemUsage;
Overview
The systemUsage
function monitors system CPU usage and memory usage over time. It calculates the average percentage CPU usage and memory usage, and returns the data in an object format.
Function Breakdown
cpuAverage()
systemUsage()
reportMem
to store memory usage data and an object reportCPU
to store CPU usage data.cpuAverage()
.reportCPU
array.reportMem
array.Exports
systemUsage
function is exported as a module.Usage
const systemUsage = require('./systemUsage');
systemUsage().then((data) => {
console.log(data);
});