Calculating current CPU usage using chrome.system.cpu

Viewed 566

I have created a simple Chrome extension that calculates the percentage of CPU usage at a certain point in time, as well as the load in between a certain time range, based on the information available via chrome.system.cpu. For the time being I have set a button on an HTML page that when pressed triggers my background.js script via messaging from my extension's contentScript.js.

'use strict';

chrome.runtime.onInstalled.addListener(function() {
  chrome.storage.sync.set({previousCpuInfo: {used: null, available: null, timestamp: false}});
});

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    chrome.storage.sync.get('previousCpuInfo', function(storageData)
    {
      chrome.system.cpu.getInfo(function(cpuInfo) {                
          var sumOfUsed = 0;
          var sumOfAvailable = 0;
          for (var i = 0; i < cpuInfo.numOfProcessors; i++)
          {
              var usage = cpuInfo.processors[i].usage;
              sumOfUsed = sumOfUsed + usage.kernel + usage.user;
              sumOfAvailable += usage.total;
          }

          var currentCpuUsage = Math.floor(sumOfUsed / sumOfAvailable * 100);
          chrome.storage.sync.set({previousCpuInfo: {used: sumOfUsed, available: sumOfAvailable, timestamp: Date.now()}});

          //Return a response. If the previous call was not within 5 seconds, and if not there was either no previous call or the previous call is from a different session.
          if ( !storageData.previousCpuInfo.timestamp || (Date.now() - storageData.previousCpuInfo.timestamp) > 5000 ) sendResponse({currentCpuUsage: currentCpuUsage, loadBetweenCalls: false});
          else sendResponse({currentCpuUsage: currentCpuUsage, loadBetweenCalls: Math.floor((sumOfUsed - storageData.previousCpuInfo.used) / (sumOfAvailable - storageData.previousCpuInfo.available) * 100)});
      });
      return true; //Required for async requests.
    });
    return true; //Required for async requests.
});
  • Example output on first click: {currentCpuUsage: 12, loadBetweenCalls: false}
  • Example output on 3 seconds later (with no power intensive processes running): {currentCpuUsage: 12, loadBetweenCalls: 4}

Unfortunately currentCpuUsage is constantly outputting 12 on my system, even when I put my CPU under strain, while loadBetweenCalls ostensibly works. This leads to my question - am I calculating the current CPU usage incorrectly?

0 Answers
Related