I am dealing with a network-related daemon: it takes data in, processes it, and spits it out. I would like to increase the performance of this daemon by profiling it and reducing it’s CPU utilization. I can do this easily on Linux with gprof. However, I would also like to use something like “time” to measure it’s total CPU utilization over a period of time. If possible, I would like to time it over a period that is less than its total run time: thus, I would like to start the daemon, wait awhile, generate CPU statistics, stop generating them, then stop the daemon at some later time.
The “time” command would work well for me, but it seems to require that I start and stop the daemon as a child of time. Is there a way to measure CPU utilization for only a portion of the daemon’s wall clock time?
The
/proc/<pid>/statfile contains the necessary information – you’re after theutimeandstimefields. Those are cumulative counters of the process’s user-mode and kernel-mode CPU time used; read them at the start of the measuring interval, then read them again at the end and calculate the difference.That will give you used CPU time in jiffies. To determine the total elapsed wallclock time in jiffies (so you can convert to an average utilisation), sum the numbers on the
cpu0line in/proc/stat(before and after, just like/proc/<pid>/stat).This is the layout of the first few fields in
/proc/<pid>/stat, fromDocumentation/filesystems/proc.txtin the Linux source: