I known that excellent replies exist on the subject for questions like:
- How to determine CPU and memory consumption from inside a process?
- Determine Process Info Programmatically in Darwin/OSX
- Get CPU percent usage
The problem is that I'm trying to use libproc.h
that defines a proc_threadinfo
structure (among others) but the field pth_cpu_usage
is always 0
(see trheadInfoHandler()
func here to see how I'm using the struct from Go).
Looking at a snippet of Chromium source here (that doesn't use libproc.h
), I was wondering if using fields from both proc_threadinfo
and proc_taskinfo
it could be possible calculate cpu percent usage.
proc_threadinfo.pth_user_time; /* user run time */
proc_threadinfo.pth_system_time; /* system run time */
proc_taskinfo.pti_total_user; /* total time */
proc_taskinfo.pti_total_system;
Edit
Some pseudo code illustrating the right algorithm or a suggestion to put me on the right path will be very appreciated.
Using /proc
filesystem I think I was able to calculate CPU % usage in Linux:
func cpuUsageOf(pid int, waitHandler func()) float32 {
stat1 := procFsStatOf(pid)
utime1 := stat1.utime // /proc/[pid]/stat field index 13
stime1 := stat1.stime // /proc/[pid]/stat field index 14
cputime1 := procFsCpuTimeTotal() // /proc/stat -> sum of cpu values
waitHandler() // here I wait 1 second
stat2 := procFsStatOf(pid)
utime2 := stat2.utime // /proc/[pid]/stat field index 13
stime2 := stat2.stime // /proc/[pid]/stat field index 14
cputime2 := procFsCpuTimeTotal() // /proc/stat -> sum of cpu values
return float32(cpuCount() * ((utime2 + stime2) - (utime1 + stime1)) * 100) / float32(cputime2 - cputime1)
}
For OS X, do I've to use values from proc_threadinfo
or proc_taskinfo
? And where I can find the same values that in Linux I read from /proc/stat
with (procFsCpuTimeTotal()
)?
Full code here (as in commit 9e34d3c72bf853ff49ef3970ad6a6c9688e9ba23
); fast link to OS X code here.