[tutorial] How to use psutil to monitor CPU and memory usage in python
What is psutil?
psutil is an open source package for python, which can help us to get the information of the system (CPU, memory, disks, network etc..).
The installation of psutil
1
pip install psutil
Usefull functions in psutil
CPU
1 2 3 4
psutil.cpu_count() # get the number of CPU psutil.cpu_percent() # get the usage of all CPU psutil.cpu_percent(percpu=True) # get the usage of per CPU psutil.cpu_percent(interval=1) # get the usage of all CPU in 1 second, using interval will get more robust result
# will get more information like buffers, cached etc.. # svmem(total=33541988352, available=25899790336, percent=22.8, used=7087771648, free=2703233024, active=15287881728, inactive=14264188928, buffers=965103616, cached=22785880064, shared=8265728, slab=904495104)
How to integrate psutil into our code?
We can use psutil to monitor each function cpu and memory usage by using decorator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import psutil
defmonitor(func): defwrapper(*args, **kwargs): process = psutil.Process() cur_func_pid = process.pid process = psutil.Process(cur_func_pid)