What is the psutil.cpu_times() method in Python?
Overview
In Python, psutil (Python system and process utilities) is a package that retrieves information on ongoing processes and system usage (CPU, memory, storage, network, and sensors). It is mostly used for system monitoring, profiling, restricting process resources, and process management.
The module can be installed via pip as follows:
pip install psutil
The cpu_times method
The cpu_times method returns the following system CPU times as a named tuple:
user: This represents the time spent by normal processes executing in the user mode.system: This represents the time spent by processes executing in the kernel mode.idle: This represents the time when the system is idle.nice: This represents the time spent by priority processes executing in the user mode.iowait: This represents the time spent waiting for I/O to complete.irq: This represents the time spent for servicing hardware interrupts.softirq: This represents the time spent for servicing software interrupts.steal: Represents the time spent by other operating systems running in a virtualized environmentguest: This represents the time spent running a virtual CPU for guest operating systems under the control of the Linux kernel.
The following attributes are available only on the Windows platform.
interrupt: This represents the time spent for servicing hardware interrupts.dpc: This represents the time spent servicing deferred procedure calls (DPCs).
All the attributes above are measured in seconds.
Syntax
psutil.cpu_times(percpu=False)
percpu: If set toTrue, the method returns CPU times for every logical CPU on the system.
Code
import psutilprint("The CPU times for the current CPU:")print(psutil.cpu_times())print("-" * 5)print("The CPU times for all the current CPUs:")print(psutil.cpu_times(True))
Explanation
- Line 1: We import the
psutilmodule. - Line 4: We retrieve the CPU times using the
cpu_timesmethod withallasFalse. Here, the values are measured in seconds. - Line 8: We retrieve the CPU times for all the CPUs using the
cpu_timesmethod withallasTrue. Here, the values are measured as percentage.