Last active
October 28, 2024 22:02
-
-
Save bag-man/5570809 to your computer and use it in GitHub Desktop.
How to calculate the current CPU load with Node.js; without using any external modules or OS specific calls.
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
var os = require("os"); | |
//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}; | |
} | |
//Grab first CPU Measure | |
var startMeasure = cpuAverage(); | |
//Set delay for second Measure | |
setTimeout(function() { | |
//Grab second Measure | |
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); | |
//Output result to console | |
console.log(percentageCPU + "% CPU Usage."); | |
}, 100); | |
With love, but mine works better: https://gist.github.com/GaetanoPiazzolla/c40e1ebb9f709d091208e89baf9f4e00 <3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That looks damn beautiful - but I can't get it to work. What's that style called? What kind of processor / compiler do you need for that?