Previously in Yuber GitHub issues saw the use of JS detection of CPU usage, feel very good.
In particular, the implementation of a bit, plus a histogram of the function can be intuitive to see the situation of CPU utilization.
See the effect: Transmission door
Realize the idea
In fact, is setinterval, using the current time minus the last execution timer record time, get a lag to reflect the CPU delay, the side reflects the CPU utilization rate.
Copy Code code 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,500 ...], but the CPU will certainly be slightly delayed, data may be [501,502,502,501,503 ...]. If the CPU usage is very high, the delay will be very large, data will become [550,551,552,552,551 ...]. By judging the change of data, we can infer the CPU usage rate preliminarily.
Use histograms to visually represent CPU usage
By drawing the histogram of data, we can see the fluctuation of the information. When the value of a certain period of a vertical graph rises, it is proved that the CPU utilization rate is higher at that time.
Copy Code code as follows:
function Drawhisto (data) {
var cvs = document.getElementById (' canvas ');
CTX = Cvs.getcontext (' 2d ');
var width = cvs.width,
Height = cvs.height,
Histowidth = width/size;
Redrawing histograms
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 only to show the effect,
~ ~ For numeric rounding equivalent to Math.floor ()
y = ~ ~ ((Data[i]-speed + 5)/(HEIGHT-10));
Ctx.moveto (X+HISTOWIDTH/2, height);
Ctx.lineto (X+HISTOWIDTH/2, height-y);
Ctx.stroke ();
}
}