Use JavaScript to detect CPU usage

  • 2020-03-30 02:24:16
  • OfStack

I have seen the method of using JS to detect CPU usage in Github Issues of yubo before, which is very good.
In particular, the implementation of their own, in addition to a histogram drawing function can see the CPU utilization.

See effect: portal

Implement ideas

SetInterval is essentially a time difference that takes the current time minus the time recorded by the last timer to reflect the delay of the CPU, which in turn reflects the CPU utilization.
var data = [],t; 
var cpuTimer = setInterval(function(){ 
t && data.push(; 
t =; 

Theoretically, the data should be [500,500,500,500...]. , but in fact the CPU will definitely be slightly delayed and the data may be [501,502,502,501,503...] . If the CPU usage is high, the latency will be large and the data will become [550,551,552,552,551...]. . By judging the changes in data, you can preliminarily infer the CPU utilization.

Use histograms to visualize CPU usage

We can see the fluctuation of data by drawing the histogram of data. When the value of a certain period in the histogram rises steeply, it proves that the CPU utilization is high at that time.
function drawHisto(data){ 
var cvs = document.getElementById('canvas'); 
ctx = cvs.getContext('2d'); 
var width = cvs.width, 
height = cvs.height, 
histoWidth = width / size; 

//Redraw histogram
ctx.fillStyle = "#fff"; 
ctx.lineWidth = histoWidth/2; 
ctx.strokeStyle = '#000'; 
for( var i = 0, len = data.length; i < len; i++){ 
var x = i * histoWidth, 
//+5, /20, -10 just to show the effect,
//~~ rounding a value 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 ); 

Related articles: