Home  >  Article  >  Web Front-end  >  Use JavaScript to detect CPU usage written by myself_javascript skills

Use JavaScript to detect CPU usage written by myself_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:54:502204browse

I saw the method of using JS to detect CPU usage in Yubo's Github Issues before, and I thought it was very cool.
I implemented it myself, and added a function to draw a histogram to visually see the CPU usage.

For the effect, please see: Portal

Implementation idea

is actually setInterval, which uses the current time to subtract the time recorded by the last timer execution to get the time difference to reflect the CPU delay , which reflects the CPU usage.

Copy code The 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 definitely be slightly delayed and the data may be [501,502,502,501,503...]. If the CPU usage is high, the delay will be large and the data will become [550,551,552,552,551...]. By judging the changes in data, the CPU usage can be initially inferred.

Use a histogram to visually represent the CPU usage

By drawing a histogram of the data, we can see the fluctuation of the data. When the value in the histogram rises sharply during a certain period, it proves that the CPU usage is high at that moment.
Copy code The 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 ;

//Redraw 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 are just for display effect,
// ~~ is the numerical rounding 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();
}
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn