Use JavaScript to detect CPU usage.

Source: Internet
Author: User

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 ();
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.