Calculation of CPU cycles in Zyphyr OS

Jyothi
2 min readNov 1, 2024

--

Zyphyr OS provides k_cycles_get_32() and k_cycles_get_64() APIs. k_cycles_get_32() and k_cycles_get_64() used to obtain the current cycle count from the hardware timer. Both functions are designed to provide high-resolution timing by accessing the fastest available hardware timer. These functions are used for benchmarking or profiling the critical sections of the code.

k_cycles_get_32() returns the 32 bit value representing current CPU cycles. This value wraps around after reaching the max value of 0xFFFFFFFF.

k_cycles_get_64() returns the 64 bit value representing the current CPU cycles if available. This function is available only if the hardware supports the 64-bit cycle counter and CONFIG_TIMER_HAS_64BIT_CYCLE_COUNTER configuration option is enabled.

sys_clock_hw_cycles_per_sec() returns the frequency of the hardware timer used for the system clock measured in cycles per second. This function is used to convert the cycle counts to milliseconds or microseconds or seconds.

The following code snippet can be used to calculate the CPU cycles of a specific code which is having a while loop:

{
uint32_t scycles, ecycles, tot_sec = 0, tot_cycles = 0;
static uint32_t cnt=1;
scycles = k_cycle_get_32();

while (…) {
//… actual code …
ecycles = k_cycle_get_32();
tot_sec = add_cycles((ecycles>scycles) ? ecycles-scycles : scycles + (0xffffffff — ecycles),
&tot_cycles, tot_sec);
scycles = ecycles;
}

printf(“\r\n %d %s : cycles %u * (clock speed %x) + %u, secs %d, msecs %d \n”,
__LINE__, __func__, tot_sec, sys_clock_hw_cycles_per_sec(), tot_cycles, tot_sec,
(tot_cycles*1000)/sys_clock_hw_cycles_per_sec());

}

uint32_t add_cycles(uint32_t cycles, uint32_t *tot_cycles, uint32_t tot_sec){
*tot_cycles += cycles;
uint32_t cpu_freq = sys_clock_hw_cycles_per_sec();
if (*tot_cycles > cpu_freq) {
tot_sec ++;
*tot_cycles %= (cpu_freq);
}
return tot_sec;
}

References:

Kernel Timing — Zephyr Project Documentation

--

--

No responses yet