Skip to content

Instantly share code, notes, and snippets.

@tkrueger
Created August 28, 2012 16:57
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save tkrueger/3500612 to your computer and use it in GitHub Desktop.
Save tkrueger/3500612 to your computer and use it in GitHub Desktop.
generate and measure CPU load with node.js
#!/usr/bin/env node
require(__dirname+"/processor-usage.js").startWatching();
var shouldRun = true;
var desiredLoadFactor = .5;
function blockCpuFor(ms) {
var now = new Date().getTime();
var result = 0
while(shouldRun) {
result += Math.random() * Math.random();
if (new Date().getTime() > now +ms)
return;
}
}
function start() {
shouldRun = true;
blockCpuFor(1000*desiredLoadFactor);
setTimeout(start, 1000* (1 - desiredLoadFactor));
}
setInterval(function() {
console.log("current process cpu usage: "+(global.processCpuUsage || 0)+"%");}
, 1000);
if (process.argv[2]) {
var value = parseFloat(process.argv[2]);
if (value < 0 || value > 1) {
console.log("please give desired load value as a range [0..1]");
process.exit(-1);
} else {
desiredLoadFactor = value;
}
}
start();
"use strict";
var fs = require('fs');
function ProcessUsageWatcher() {
global.pubcrawler = global.pubcrawler || {};
global.pubcrawler.processCpuUsage = 0;
}
ProcessUsageWatcher.prototype = {
startWatching: function() {
if (this.interval) {
return;
}
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);
});
};
this.interval = setInterval(function(){
getUsage(function(startTime){
setTimeout(function(){
getUsage(function(endTime){
var delta = endTime - startTime;
var percentage = 100 * (delta / 500);
global.processCpuUsage = percentage;
});
}, 5000);
});
}, 1000);
},
stopWatching : function() {
if (this.interval) {
clearInterval(this.interval);
}
}
};
var instance = new ProcessUsageWatcher();
exports.startWatching = instance.startWatching;
exports.stopWatching = instance.stopWatching;
#!/usr/bin/env node
require(__dirname+"/processor-usage.js").startWatching();
var shouldRun = true;
function blockCpu() {
var result = 0;
while(shouldRun) {
result += Math.random() * Math.random();
}
return result;
}
function start() {
shouldRun = true;
blockCpu();
setTimeout(stop, 1000);
}
function stop() {
console.log("Stopping cpu hog");
shouldRun = false;
}
start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment