How to get CPU usage in JavaScript?
Asked Answered
A

6

39

Is there a way to get the CPU(s) usage in JavaScript on the browser?

Abrasion answered 15/9, 2016 at 17:22 Comment(2)
The link that suggest the duplication does not exist any moreBenn
There is a way to check it in Node.js and request it in Javascript.Mundane
D
20

From what I have gathered, the most you can find out natively in the browser about JS CPU stats, is the amount of CPU cores the client is using. Insert this in your JS file:

console.log(navigator.hardwareConcurrency)

You can then check that in the Chrome Dev Tools console.

However, you can calculate the CPU load using Node.js. Here is a step-by-step on that.

The answer on this page may also be of help in your dilemma: Javascript- Dynamically monitor CPU/memory usage

Durango answered 15/9, 2016 at 18:23 Comment(3)
Is there any way to get only the CPUs that are being used by a node process? os.cpus() gets all the CPUs in a system, doesn't it?Crandale
It returns me 4?Superconductivity
Does not work on firefox and the information given is almost unusable, no link to CPU usage at all, only number of CPUs, which can mean everythingDismissal
D
6

Essentially, no. BUT... and this is a big BUT, if your application is an SPA you could consider deploying it via Electron.

If you did this you could then access the CPU usage: https://electronjs.org/docs/api/structures/cpu-usage

For you it's not a big leap to move from the web to Electron. But for your users it's a big change from accessing something in the browser to downloading an app. However, if this is a very important feature of your app/service then it might be worth it...

Dialytic answered 5/4, 2019 at 10:37 Comment(1)
Even if your app is not targeting Electron, it's possible to deploy any SPA to Electron and you can monitor the CPU usage there.Drysalter
P
2

The answer you may be looking for is measuring the current CPU intensitivity.

if((new Date()).getDay()==6){}else{

work = new Worker("data:text/javascript,setInterval(` dl=Date.now();for(itr=1;itr<1000;itr++){};dl=Date.now()-dl;postMessage(dl);`,1000);");

work.onmessage = (evt)=>{
     console.info(12 - evt.data+(' point'+((new Intl.PluralRules(navigator.language)).select(12-evt.data)=='one'?'':'s')))
       };
   }

Workers would measure the CPU speed of looping.

Powwow answered 11/8, 2022 at 6:17 Comment(0)
C
1

Here's a more interesting and interactive example of how you might measure CPU performance with Javascript.


The following example uses a WebWorker to record the number of loop cycles performed. This data can be used as a relative benchmark of CPU performance.

Do note that this may not result in the best user experience, since it does take up a significant portion of the user's CPU.

const blob = new Blob(
  [
    `let time = performance.now()
           let iterations = 0;
           while(true){
                iterations++;
                let now = performance.now()
                if(now - time > 100){
                    postMessage(iterations)
                    time = performance.now()
                    iterations = 0
                }
           }`,
  ], {
    type: "text/javascript"
  }
);

const processWorker = new Worker(window.URL.createObjectURL(blob));

const performanceData = [];

processWorker.onmessage = (e) => {
  performanceData.push(+e.data);
  chart.data.datasets[0].data = performanceData.slice(-50);
  chart.update();
};

const chart = new Chart(document.getElementById("line-chart"), {
  width: 400,
  height: 200,
  type: "line",
  data: {
    labels: Array(50).fill(""),
    datasets: [{
      data: performanceData,
      borderColor: "#0f796b",
      fill: !0,
      fillColor: "#96c4be",
      tension: 10,
      cubicInterpolationMode: "monotone"
    }]
  },
  options: {
    scales: {
      y: {
        min: 0,
      }
    },
    title: {
      display: !1
    },
    plugins: {
      legend: {
        display: !1
      }
    },
    animation: {},
    elements: {
      point: {
        radius: 0,
        opacity: 0
      }
    }
  }
});
<div style="height: 200px; width: 400px">
  <canvas id="line-chart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
Chronometry answered 29/11, 2023 at 22:42 Comment(0)
E
0

On nodeJS there is a library : systeminformation npm systeminformation This library provides system information like CPU, Memory, battery, and more, on several OS: Windows, Linux, Sun, and Mac. It requires Node, I do not think it would work on webapp.

Eutectoid answered 27/3, 2023 at 12:51 Comment(0)
R
0

Since the question says:

on the browser

Maybe it's helpful to know that Microsoft Edge(not sure if it's exclusive) has a tab called "Performance Monitor" inside it's dev tools. It shows CPU Usage, JS Heap size, etc.

Readership answered 19/6, 2023 at 23:56 Comment(2)
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From ReviewIrmine
@Irmine I thought I was doing this by mentioning the tab's existence inside the dev tools. I'm not sure what else I would need to provide, the link is just a more extensive explanation of what the performance monitor does. The link changing wouldn't change the answer. Could you please clarify what I need to add or change to give a complete answer?Readership

© 2022 - 2024 — McMap. All rights reserved.