SoFunction
Updated on 2025-03-02

Implementation method of obtaining system CPU information in Python operation and maintenance

When using Python for operation and maintenance work, sometimes you need to obtain CPU information, which is very easy to implement with the help of the psutil module library.

There are several common CPU information:

1. User time and percentage;

2. System time and percentage;

3. Free time and percentage;

4. CPU hardware information;

The time in the first 3 can be obtained using the cpu_times method, and the percentage can be obtained using cpu_times_pcercent.

A simple demonstration is as follows:

In [9]: importpsutil
 
In [10]:psutil.cpu_times()
Out[10]: scputimes(user=4206.828125,system=2574.46875, idle=128393.578125)
 
In [11]:psutil.cpu_times_percent()
Out[11]:scputimes(user=3.6, system=2.4, idle=94.0)
 
In [12]:psutil.cpu_times().idle
Out[12]:128616.46875
 
In [13]:psutil.cpu_times_percent().user
Out[13]: 3.5
 
In [14]:psutil.cpu_times_percent().idle
Out[14]: 94.1

From the above information, we can see that my current computer is completely overperformance! It seems that when choosing a computer in the future, the CPU won't have to choose that strong, but the hard drive must be selected as a better one.

As for the CPU physical information in the previous item 4, it is generally to obtain the number of logical CPUs of the CPU and the number of physical cores of the CPU, which can be obtained using the cpu_count method.

A simple demonstration is as follows:

In [15]:psutil.cpu_count()
Out[15]: 8
 
In [16]:psutil.cpu_count(logical = False)
Out[16]: 4

From the above interactive command, the information obtained is: the computer has four cores and eight threads. When I chose a computer before, I basically came for this U. Now, looking at the capabilities of this computer, it seems that it can still be used for a while.

The above article on Python operation and maintenance to obtain system CPU information is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.