LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Percentage of CPU used on a single process (https://www.linuxquestions.org/questions/programming-9/percentage-of-cpu-used-on-a-single-process-750899/)

Aztral 08-28-2009 11:31 AM

Percentage of CPU used on a single process
 
I know that the utime and stime (user and system) jiffies can be obtained in /proc/pid/stat. So to obtain percentage of cpu used on a single process the options are to do

(process utime + stime)/(total jiffies spent over a time interval),

which would give me the percentage of total available CPU that process used), or to do

(utime + stime)/(total jiffies - idle jiffies), which would give me the percentage of actual used CPU over that interval that was used on the specific process.

Is my logic correct here? In the end I would like to come up with something similar to top, but neither value is similar at all.

As far as I can tell top just adds the process utime+stime, subtracts the old utime+stime, then divides by elapsed where elapsed is:

elapsed = timediff.tv_sec * HZ + (timediff.tv_usec * HZ) / 1000000;

I'm not sure what is being done here. elapsed = the number of HZ that have occurred since the last time top was updated? Why would that be used rather than the total jiffies spent (or total - idle)? Guess I'm asking for someone to explain the fallacies in my logic =).

Thanks

neonsignal 09-04-2009 08:38 AM

Code:

elapsed = timediff.tv_sec * HZ + (timediff.tv_usec * HZ) / 1000000;
elapsed is the number of jiffies that have occurred since the last sampling by top. It is simply calculating:

Code:

elapsed (jiffies) = time (s) * HZ (jiffies/s)
What top is giving is an approximation of the instantaneous CPU usage by the task (as a percentage):

Code:

usage% = 100% * elapsed_utime_stime (jiffies) / elapsed (jiffies)
If you instead use the cumulative utime_stime, you would need to divide by the cumulative elapsed jiffies since the start of the process, and you would be measuring the average CPU usage of that process. This is less useful, since other processes may have been running on and off during that time, and so the average will not be consistent. Instead, top reports the (more useful) total CPU time that the process has used:

Code:

cumulative (s) = cumulative_utime_stime (jiffies) / HZ (jiffies/s)


All times are GMT -5. The time now is 09:00 PM.