So guys heres my code:
import os from "os";
import process from "process";
export const getCpuInfo = () => {
const cpuUsage = process.cpuUsage();
const totalCpuUsage = cpuUsage.user + cpuUsage.system;
const numCPUs = os.cpus().length;
// Calculate the total CPU time in seconds
const totalCpuTime = process.uptime();
// Calculate the CPU usage percentage
const cpuUsagePercentage = (totalCpuUsage / (totalCpuTime * 1e6)) * 100;
let modelName;
let modelSpeed;
let displayed = false;
os.cpus().forEach(cpu => {
if (displayed) return;
modelName = cpu.model;
modelSpeed = cpu.speed;
return displayed = true;
})
return {
cpuSpeed: formatHertz(modelSpeed),
cpuModel: modelName,
cpuCores: numCPUs,
cpuParallelism: os.availableParallelism(),
cpuUsage: cpuUsagePercentage.toFixed(2) // Format as a percentage with 2 decimal places
}
}
function formatHertz(megaHertz) {
try {
let hertz = Number(megaHertz);
let Ghz = hertz / 1000;
return `${Ghz.toFixed(2)} Ghz`; // Round to 2 decimal places
} catch (err) {
return err;
}
}
function convertNumberFormat(number) {
const megahertz = number / 1e6; // Convert to megahertz
return megahertz.toFixed(2); // Return with 2 decimal places
}
But I am actually not able to get the cpu usage percentage
I tried using third party-libraraies but they didn’t worked as I wanted.
I want the cpu usage percentage to get displayed in the format like: 22.23%
Can anyone help me with above code?
I am using windows btw
Thanks in advance
2
Here how you can get cpu percentage in express:
`const os = require("os");
// Function to get CPU info
const getCPUInfo = () => {
const cpus = os.cpus();
let totalIdle = 0,
totalTick = 0;
cpus.forEach((core) => {
for (type in core.times) {
totalTick += core.times[type];
}
totalIdle += core.times.idle;
});
return { idle: totalIdle, total: totalTick };
};
// Function to calculate CPU percentage
const calculateCPUUsage = (start, end) => {
const idleDifference = end.idle - start.idle;
const totalDifference = end.total - start.total;
const percentageCPU =
100 - Math.floor((100 * idleDifference) / totalDifference);
return percentageCPU;
};
// Initial CPU information
let startMeasure = getCPUInfo();
// Function to get CPU percentage at intervals
const getCPUPercentage = () => {
const endMeasure = getCPUInfo();
const cpuPercent = calculateCPUUsage(startMeasure, endMeasure);
startMeasure = endMeasure; // Update startMeasure for the next interval
return cpuPercent;
};
// Example Express.js route to return CPU usage
const express = require("express");
const app = express();
app.get("/cpu-usage", (req, res) => {
const cpuPercentage = getCPUPercentage();
res.json({ cpuUsage: `${cpuPercentage}%` });
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
2