Previously, I saw the method of using JS to detect CPU usage in yuber's Github Issues, and I think it is awesome.
Specifically, I implemented it myself, and added a histogram function to intuitively view the CPU usage.
For the effect, see portal
Implementation idea
In fact, it is setInterval. the time difference between the current time and the time when the last timer record is executed is obtained to reflect the CPU latency and the CPU usage.
Copy codeThe Code is as follows:
Var data = [], t;
Var cpuTimer = setInterval (function (){
T & data. push (Data. now ()-t );
T = Data. now ();
},500 );
Theoretically, the data should be [500,500,500,500,500...], but in fact the CPU will certainly be slightly delayed, and the data may be [501,502,502,501,503...]. If the CPU usage is high, the latency will be high, and the data will change to [550,551,552,552,551...]. By judging the data changes, we can preliminarily infer the CPU usage.
Use a histogram to visually Display CPU usage
By drawing a histogram of data, we can see data fluctuations. When the value of a period in the histogram rises sharply, the CPU usage is high at that time.
Copy codeThe Code 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;
// Re-paint the 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 only for display effect,
//~~ An integer 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 ();
}
}