How do I calculate %CPU in my own libvirt programs?
By the way, Qiita seems to be able to use the $ \ LaTeX $ notation.
libvirt doesn't have a method to get the CPU usage of the domain directly, but according to the above article, it seems that the usage can be calculated from the CPU usage time. The following is the story of libvirt-python.
Documents are being prepared. http://libvirt.org/docs/libvirt-appdev-guide-python/en-US/html/index.html
First, connect to libvirtd.
import libvirt
con = libvirt.openReadOnly()
dom0 = con.listAllDomains()[0]
dom0
is the domain.
With dom0.info ()
, you can get how many seconds the CPU has been used since the domain was started in nanoseconds ($ cpuTime $). The data structure is virDomainInfo. Fifth value.
cpuTime = dom0.info()[4]
If you get this every $ t $ seconds, the CPU usage of your domain will be
\frac{cpuTime_{now} - cpuTime_{now-t}}{t \times nrCores \times 10^9}\times 100
$ nrCores $ indicates the number of physical cores in the system and can be obtained with con.getInfo ()
(virNodeInfo) ..
If you want to know the CPU usage rate for each core, you can use dom0.vcpus ()
to get the CPU usage time for each core (virVcpuInfo. -libvirt-domain.html # virvcpuInfo)). In this case, $ nrCores $ is 1 or 2 if hyperthreading is working.