how to calculate CPU utilization?

Dan Nelson dnelson at allantgroup.com
Sat Feb 12 12:16:57 PST 2005


In the last episode (Feb 12), Nimnod said:
> i am looking for how to accurately calculate the CPU utilization per
> process. i have looked through the top sources, and found out it's
> using the kvm lib, which isn't suitable for my purpose.

Why not?  You don't need to be setuid root to call kvm functions; when
possible they fetch their info via sysctl.  Neither top nor ps are
setuid.

> is there a way to accurately calculate %CPU based on information from
> the struct proc ? it does carry info on proc time (p_runtime),
> system, user and interrupt ticks, and previous system, user and int
> times in usec, but i just can't make the right equation to get the
> appropriate values. first, i attempted to divide the process runtime
> by system uptime, which seemed ok, but obviously this is not the way.
> could anyone please help?

You need to take two samples separated by some delay (1 or 5 seconds
maybe), then take their difference and divide by the delay.  That will
give you the cpu usage over that period.

-- 
	Dan Nelson
	dnelson at allantgroup.com


More information about the freebsd-hackers mailing list