glenreesor / HammerBar

A Windows-Like Taskbar for MacOS
GNU General Public License v3.0
16 stars 4 forks source link

CPU widget regularly shows over 100% usage even when in idle #6

Open daveedmee opened 1 month ago

daveedmee commented 1 month ago

I'm currently checking how many colors we need and activated all widgets the same way u described in the readme.

The CPU widgets regularly show numbers above 100%. There seem to be an error in either the way the widget is programmed or initialized because while the CPU widgets shows usage of around 150-300% mac task manager stays around 20-25%

Bildschirmfoto 2024-10-04 um 13 15 06

Just missed when the CPU meter showed 435%

Bildschirmfoto 2024-10-04 um 13 23 57

Example of difference in usage percents

glenreesor commented 1 month ago

Ah, there are a couple of things going on here.

The first is that the method I put in the README was adding all the %cpu reported for individual processes. However I believe those percents are relative to a single CPU core -- i.e. if they add up to 100% you're using the equivalent of one CPU core. So the number of cores on your system will determine what the highest possible % that can be. For example my Mac has 4 cores so if it was completely using all cores, the CPU monitor in HammerBar would max out at 400%.

The second thing is I'm not entirely sure if those % values reported for individual processes include the "system" portion of the cpu load.

I've done some research, and I believe a better way to do this is using the top command which (a) reports as a percent of the total cores of the system, so the maximum will be a more sane 100% and (b) it separates user and system for you, so they just have to be summed.

So replacing the getCurrentCpuUsage() in your init.lua with the following should do the trick. Seems to work for me, but my mac is really slow so it can be tough to confirm if the values are matching the mac task manager. If it works for you, I'll update the README.

function getCurrentCpuUsage()
  local handle = io.popen('top -l 1')
  local result = handle:read('*a')
  handle:close()

  -- Extract the CPU user and sys values from the result
  local user, sys = result:match('CPU usage: (%d+%.%d+)%% user, (%d+%.%d+)%% sys')

  -- Convert to numbers and sum them
  local total_usage = tonumber(user) + tonumber(sys)

  return total_usage
end