23

Is there a way to find out the cpu usage in % for a node.js process via code. So that when the node.js application is running on the server and detects the CPU exceeds certain %, then it will put an alert or console output.

6 Answers 6

32

On *nix systems can get process stats by reading the /proc/[pid]/stat virtual file.

For example this will check the CPU usage every ten seconds, and print to the console if it's over 20%. It works by checking the number of cpu ticks used by the process and comparing the value to a second measurement made one second later. The difference is the number of ticks used by the process during that second. On POSIX systems, there are 10000 ticks per second (per processor), so dividing by 10000 gives us a percentage.

var fs = require('fs');

var getUsage = function(cb){
    fs.readFile("/proc/" + process.pid + "/stat", function(err, data){
        var elems = data.toString().split(' ');
        var utime = parseInt(elems[13]);
        var stime = parseInt(elems[14]);

        cb(utime + stime);
    });
}

setInterval(function(){
    getUsage(function(startTime){
        setTimeout(function(){
            getUsage(function(endTime){
                var delta = endTime - startTime;
                var percentage = 100 * (delta / 10000);

                if (percentage > 20){
                    console.log("CPU Usage Over 20%!");
                }
            });
        }, 1000);
    });
}, 10000);
Sign up to request clarification or add additional context in comments.

1 Comment

Is it per processor or per processor core?
18

Try looking at this code: https://github.com/last/healthjs

Network service for getting CPU of remote system and receiving CPU usage alerts...

Health.js serves 2 primary modes: "streaming mode" and "event mode". Streaming mode allows a client to connect and receive streaming CPU usage data. Event mode enables Health.js to notify a remote server when CPU usage hits a certain threshold. Both modes can be run simultaneously...

5 Comments

This hasnt been updated in a long time and doesnt seem to work any more.
You dont mark me down for it... its not my fault! I made that comment a year ago.
Answers get marked down so other people won't refer to them as truth, it's nothing personal.
You should delete this answer if you know that it is no longer correct. Or atleast the OP should remove his correct answer check.
This is SO, not ServerFault... contribute to the code or use it as an example.
10

Use node process.cpuUsage function (introduced in node v6.1.0). It shows time that cpu spent on your node process. Example taken from docs:

const previousUsage = process.cpuUsage();
// { user: 38579, system: 6986 }

// spin the CPU for 500 milliseconds
const startDate = Date.now();
while (Date.now() - startDate < 500);

// At this moment you can expect result 100%
// Time is *1000 because cpuUsage is in us (microseconds)
const usage = process.cpuUsage(previousUsage);
const result = 100 * (usage.user + usage.system) / ((Date.now() - startDate) * 1000) 
console.log(result);

// set 2 sec "non-busy" timeout
setTimeout(function() {
    console.log(process.cpuUsage(previousUsage);
    // { user: 514883, system: 11226 }    ~ 0,5 sec
    // here you can expect result about 20% (0.5s busy of 2.5s total runtime, relative to previousUsage that is first value taken about 2.5s ago)
}, 2000);

5 Comments

He asked for percentage, though
@AmitB. to get % use some simple math. You need to divide result by time passed between measures. percentResult = 100 * (result.user + result.system) / ((timeOfCurrentDateNow - timeOfPreviousDateNow) * 1000). Time is multiplied by 1000 to convert ms to us - process.cpuUsage returns results in us. Note that this is result for single Node process operating on single logical core.
process.cpuUsage just returns how much time passed
@EvgenyKolyakov yes and you can use this to calculate cpu usage in % in certain time period (in above case it analyzes how much time CPU spent on this process during last 500 millis. To get % in this specific case it is enough to do usageInPercent = (usage.user + usage.system)/500.
Btw. cpu usage conception have only sense in case of measuring it in some time window (eg. last minute or second)
8

You can use the os module now.

var os = require('os');
var loads = os.loadavg();

This gives you the load average for the last 60seconds, 5minutes and 15minutes. This doesnt give you the cpu usage as a % though.

3 Comments

load average is for the entire system. The question is about getting the stats for the current process.
NOTE!! Returns [0,0,0] on Windows.
@origin1tech to enable it on Windows use loadavg-windows from npm
7

see node-usage for tracking process CPU and Memory Usage (not the system)

Comments

0

Another option is to use node-red-contrib-os package

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.