I saw a method of using JS to detect CPU usage in Yu Bo’s Github Issues before, and I thought it was great.
I have implemented it myself, and added a function of drawing histograms to visually see the CPU usage.
See the effect: Portal
Realize the idea
In fact, it is setInterval, which uses the current time to subtract the time of the last time executed by the timer record to obtain the time difference to reflect the CPU delay, which indirectly reflects the CPU usage rate.
The code copy is as follows:
var data = [],t;
var cpuTimer = setInterval(function(){
t && data.push(Data.now()-t);
t = Data.now();
},500);
In theory, the data should be [500,500,500,500...], but in fact the CPU will definitely delay slightly, and the data may be [501,502,502,501,503...]. If the CPU usage rate is high, the latency will be very large and data will become [550,551,552,552,551...]. By judging the change in data, the CPU usage rate can be initially inferred.
Intuitive representation of CPU usage using histogram
By drawing a histogram of data, we can see the fluctuations of the data. When the value of a certain period of time in the histogram rises sharply, it proves that the CPU usage rate is high at that moment.
The code copy is as follows:
function drawHisto(data){
var cvs = document.getElementById('canvas');
ctx = cvs.getContext('2d');
var width = cvs.width,
height = cvs.height,
histoWidth = width / size;
// Repaint histogram
ctx.fillStyle = "#fff";
ctx.fillRect(0,0,width,height);
ctx.beginPath();
ctx.lineWidth = histoWidth/2;
ctx.strokeStyle = '#000';
for( var i = 0, len = data.length; i < len; i++){
var x = i * histoWidth,
// +5, /20, -10 is just for the purpose of displaying the effect,
// ~~ is a numerical value that is equivalent to Math.floor()
y = ~~( (data[i] - speed + 5) / 20 * (height-10) );
ctx.moveTo(x+histoWidth/2, height );
ctx.lineTo(x+histoWidth/2, height-y);
ctx.stroke();
}
}