Skip to content

Instantly share code, notes, and snippets.

@wirelessr
Created December 20, 2021 02:05
Show Gist options
  • Save wirelessr/8ed5e70d7788c12054f5cad8e10c5f87 to your computer and use it in GitHub Desktop.
Save wirelessr/8ed5e70d7788c12054f5cad8e10c5f87 to your computer and use it in GitHub Desktop.
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