Count CPU cycles on ESP32 with esp_cpu_get_cycle_count
Time a code section on ESP32 in CPU cycles with esp_cpu_get_cycle_count, then convert to microseconds from the CPU frequency. ESP-IDF v5.4, C99.
esp_cpu_get_cycle_count returns the core's own cycle counter as a 32-bit value, which is finer than the 1 microsecond of esp_timer_get_time. Read it before and after a section and subtract. Unsigned subtraction handles the wrap of the counter, so the difference is right even if it rolled over in between.
#include <stdint.h>
#include "esp_cpu.h"
#include "esp_log.h"
#include "sdkconfig.h"
void time_section(void (*fn)(void)) {
esp_cpu_cycle_count_t start = esp_cpu_get_cycle_count();
fn();
esp_cpu_cycle_count_t cycles = esp_cpu_get_cycle_count() - start;
uint32_t us = cycles / CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ;
ESP_LOGI("perf", "%lu cycles = %lu us", (unsigned long)cycles, (unsigned long)us);
}For a function that spends 48000 cycles on a core configured for 240 MHz:
I (402) perf: 48000 cycles = 200 usThe count on your board will differ, and it moves from run to run with cache misses and interrupts. Two limits matter. The counter is per core, so read both values on the same core, which means pinning the task. And a 32-bit counter at 240 MHz wraps in about 17.9 seconds, so it only suits short sections. The division is right only while the CPU frequency matches the config value; if you use dynamic frequency scaling, read the current frequency instead. See the system API reference.