js 获取当前网速 及 cpu占用率

一:获取当前网速

function networkSpeed() {
    let startTime = Date.now();
    let xhr = new XMLHttpRequest();
    xhr.open("GET", "https://upload.wikimedia.org/wikipedia/commons/2/2d/Snake_River_%285mb%29.jpg");

    xhr.onload = function () {
        let duration = (Date.now() - startTime) / 1000;
        let size = xhr.getResponseHeader("Content-Length") / 1024 / 1024; //  图片大小5M
        let speed = (size / duration).toFixed(2);
        console.log(speed + "mb/s当前网速 ");
    };
    xhr.send();
    console.log(navigator.hardwareConcurrency)
}

一:获取当前cpu占用率

function getCpu() {
    let data = [];
    let t;
    let getNow = function () {
        return new Date().getTime();
    };
    let date = getNow();

    function pulse() {
        t && data.push(Date.now() - t);
        t = Date.now();
        let set = setTimeout(pulse, 50); // 原理自己吾 
        let nums = ""; // 50 - 55 正常、 55 - 60 轻微卡顿、 60 以上卡顿
        (getNow() - date) / 1000 > 1 && (nums = (data.reduce((a, b) => a + b) / data.length).toFixed(2));
        (getNow() - date) / 1000 > 1 && console.log(nums);
        (getNow() - date) / 1000 > 1 && clearTimeout(set);
    }
    pulse()
}

你可能感兴趣的:(js 获取当前网速 及 cpu占用率)