Conky-for-macOS / conky-for-macOS

macOS port of the Light-weight system monitor for X.
https://github.com/Conky-for-macOS/conky-for-macOS/wiki
GNU General Public License v3.0
152 stars 9 forks source link

Maximise precision of process % CPU usage #15

Closed npyl closed 6 years ago

npyl commented 6 years ago

Currently we calculate the % CPU usage by finding the total CPU usage only ONCE, when get_top_info() is called and we use it for all processes.

Below is the algorithm used:

ALGORITHM get_top_info
VARIABLES:
LONG total                      ! total CPU usage
LONG pu                         ! a process' CPU usage
INT percentage              ! a process' % CPU usage

START
total = GET_TOTAL_CPU_USAGE()

FOR_EACH proc IN processesArray DO

pu = GET_PROC_USAGE( proc )
percentage = ( pu / total ) * 100

END_FOR_EACH
END_ALGORITHM

Precision can be optimised if we move the |total| before the |pu| -- inside the for-each loop.

ALGORITHM get_top_info
VARIABLES:
LONG total                      ! total CPU usage
LONG pu                         ! a process' CPU usage
INT percentage              ! a process' % CPU usage

START
FOR_EACH proc IN processesArray DO

total = GET_TOTAL_CPU_USAGE()
pu = GET_PROC_USAGE( proc )
percentage = ( pu / total ) * 100

END_FOR_EACH
END_ALGORITHM

The goal is to implement this in conky but there are some problems keeping me back at the moment. More info coming soon!

npyl commented 6 years ago

And there is a second which fixes the algorithm a bit: cd1d1fbbd57ec4a2b176b6dfdd2f8231a8e05060

npyl commented 6 years ago

This is a small image of the process struct:

    unsigned long user_time;
    unsigned long total;
    unsigned long kernel_time;
    unsigned long previous_user_time;
    unsigned long previous_kernel_time;
    unsigned long total_cpu_time;

Lets suppose that in the struct exist two more variables:

current_user_time current_kernel_time

which we define as the measurements of a process' time in userspace and kernelspace respectively in current iteration.

In this case, based on linux.cc we understand the following:

and

Based on the pattern, total would mean the delta!

npyl commented 6 years ago

The commit 36af37475b76cc1eb3752de2484ff4f3f8eb3135 improved the get_cpu_sample() function leading to correct calculations and fixed the problem of get_top_info() where some values would become 0... Seems like there was a problem with the API

Now get_top_info() shows nearly the same CPU usage as Activity Monitor!