Index
MicroPython doesn’t run a full operating system, so there’s no built-in “CPU usage” function like top
or htop
. But you can measure how busy your ESP32 is by using a simple trick: compare how much time is spent doing nothing (idle) versus doing work.
In this blog post, we’ll:
- Understand how CPU usage works in bare-metal systems
- Use a timer-based method to estimate CPU usage
- Show complete code to monitor CPU load in MicroPython
How CPU Usage Estimation Works
We measure CPU load by:
- Counting how often an “idle loop” runs in 1 second (when nothing else is running).
- Then, during actual tasks, compare how many idle loops run.
- The difference gives an idea of how much CPU was busy.
Step-by-Step: MicroPython Code to Estimate CPU Usage
Here’s the full code that shows CPU usage in percentage:
import time
import machine
# Number of idle loop iterations in a second when idle
IDLE_BASELINE = 0
# Measure baseline idle loop count
def measure_idle_baseline(duration=1):
print("Calibrating idle baseline...")
start = time.ticks_ms()
counter = 0
while time.ticks_diff(time.ticks_ms(), start) < duration * 1000:
counter += 1
print("Baseline idle loops per second:", counter)
return counter
# Simulate a task (replace with your real workload)
def do_work(duration=0.5):
start = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), start) < duration * 1000:
# Simulate CPU task
sum(i * i for i in range(100))
# Measure CPU usage over a given duration
def measure_cpu_usage(idle_baseline, duration=1):
start = time.ticks_ms()
idle_count = 0
while time.ticks_diff(time.ticks_ms(), start) < duration * 1000:
idle_count += 1
usage = 100 - int((idle_count / idle_baseline) * 100)
if usage < 0:
usage = 0
print("CPU Usage:", usage, "%")
return usage
# MAIN LOOP
IDLE_BASELINE = measure_idle_baseline()
while True:
do_work(0.6) # Simulate 60% CPU work
measure_cpu_usage(IDLE_BASELINE)
time.sleep(1)
What It Does
- Calibrates the idle speed of the loop for 1 second when idle (no tasks).
- In each cycle:
- Simulates a workload (or replace with your real task).
- Measures how much idle time was left.
- Calculates usage = (baseline – idle) / baseline.
Sample Output
Calibrating idle baseline...
Baseline idle loops per second: 64534
CPU Usage: 58 %
CPU Usage: 61 %
CPU Usage: 59 %
⚠️ Notes
- This is a relative estimation, not an exact measurement.
- It’s great for checking if your loop is too tight or overloaded.
- You can integrate this into your logs or diagnostics for battery-powered or real-time devices.