Using JavaScript to detect CPU usage _javascript skills written by yourself

Source: Internet
Author: User
Tags setinterval cpu usage
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 ();
}
}
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.