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)