Created
December 20, 2021 02:05
-
-
Save wirelessr/8ed5e70d7788c12054f5cad8e10c5f87 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const os = require('os'); | |
// Take the first CPU, considering every CPUs have the same specs | |
// and every NodeJS process only uses one at a time. | |
const cpus = os.cpus(); | |
const cpu = cpus[0]; | |
// Accumulate every CPU times values | |
const total = Object.values(cpu.times).reduce( | |
(acc, tv) => acc + tv, 0 | |
); | |
// Normalize the one returned by process.cpuUsage() | |
// (microseconds VS miliseconds) | |
const usage = process.cpuUsage(); | |
const currentCPUUsage = (usage.user + usage.system) * 1000; | |
// Find out the percentage used for this specific CPU | |
const perc = currentCPUUsage / total * 100; | |
console.log(`CPU Usage (%): ${perc}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment