Simple %CPU usage for a domain is calculated by sampling
virDomainGetInfoperiodically and looking at the
virDomainInfocpuTime field. This 64 bit field counts nanoseconds of CPU time used by the domain since the domain booted.
tbe the number of seconds between samples. (Make sure that
tis measured as accurately as possible, using something like
gettimeofday(2)to measure the real sampling interval).
cpu_time_diffbe the change in
cpuTimeover this time, which is the number of nanoseconds of CPU time used by the domain, ie:
cpu_time_diff = cpuTimenow — cpuTimet seconds ago
nr_coresbe the number of processors (cores) on the system. Use virNodeGetInfo to get this.
Then, %CPU used by the domain is:
Because sampling doesn't happen instantaneously, this can be greater than 100%. This is particularly a problem where you have many domains and you have to make a
%CPU = 100 × cpu_time_diff / (t × nr_cores × 109)
virDomainGetInfocall for each one.