How to Get Individual CPU Core Usage in Python Using psutil
Monitoring system performance is a fundamental task for system administrators, backend developers, and software engineers. If you are building a system dashboard, performance monitor, or profiling multi-threaded applications in Python, total CPU usage might not give you the full picture. Often, you need to measure the utilization of each individual CPU core separately.
Fortunately, Python's standard cross-platform system monitoring library, psutil, makes retrieving per-core metrics remarkably easy. In this guide, we will cover how to use psutil to fetch per-core CPU stats and discuss important implementation details.
The Quick Solution
To get the usage percentage of each individual CPU core, use the psutil.cpu_percent() function and pass the argument percpu=True.
import psutil
# Fetch CPU percentage for each core over a 1-second interval
per_core_usage = psutil.cpu_percent(interval=1, percpu=True)
for core_num, percentage in enumerate(per_core_usage):
print(f"Core {core_num}: {percentage}%")
Understanding Key Parameters
- percpu=True: This parameter instructs
psutilto return a list of floats representing the utilization percentage of each logical CPU core. If left as default (False), it returns a single float for overall system usage. - interval=1: CPU usage is calculated by comparing system CPU times over a time interval. Setting
interval=1causes the function to block for 1 second and return the average utilization across that timeframe.
Handling Non-Blocking Continuous Calls
If you are running a continuous monitoring loop (such as in a GUI or web API endpoint) and do not want to block execution using interval=1, you can pass interval=None or call the function periodically without blocking.
import psutil
import time
# First call initializes baseline measurements (returns 0.0 or initial values)
psutil.cpu_percent(percpu=True)
# Simulate non-blocking periodic tracking inside a loop
for _ in range(3):
time.sleep(1) # Doing other work here...
core_usage = psutil.cpu_percent(interval=None, percpu=True)
print(core_usage)
Note: The very first time psutil.cpu_percent() is called with interval=None, it will return 0.0 for all cores because it has no previous reference point to compare against.
Advanced: Detailed CPU Time Breakdown Per Core
If you need deeper insight into how each core splits work between user applications, system processes, and idle time, use psutil.cpu_times_percent():
import psutil
core_times = psutil.cpu_times_percent(interval=1, percpu=True)
for i, core in enumerate(core_times):
print(f"Core {i} -> User: {core.user}%, System: {core.system}%, Idle: {core.idle}%")
Summary
Tracking per-core performance in Python requires just one line of code with psutil.cpu_percent(percpu=True). By understanding the interval argument, you can easily integrate real-time core monitoring into non-blocking background workers or real-time performance dashboards.