5

I want to measure how long does a single function take on STM32. The only thing I could find is SysTick_Handler. However, that is an periodic interrupt, but what I need is get time interval like:

long t1 = mcu_clock();
sleep(20);
long t2 = mcu_clock();
long diff = (t2 - t1);

I've tried C clock(), but it didn't work and always return -1. How can I make it?

Kevin Dong
  • 5,001
  • 9
  • 29
  • 62
  • Increment a variable in the `SysTick_Handler` and query that variable. – Bence Kaulics Feb 15 '17 at 10:08
  • @BenceKaulics Is that the only solution? It seems like a workaround. – Kevin Dong Feb 15 '17 at 10:09
  • You have to set up a timer in either way and keep track of it. The easiest to use the sys tick and a simple variable. The official HAL library from ST does it the same way, example: [stm32F0xx_hal.c](https://github.com/wemos/Motor_Shield_Firmware/blob/master/Drivers/STM32F0xx_HAL_Driver/Src/stm32f0xx_hal.c) – Bence Kaulics Feb 15 '17 at 10:17

2 Answers2

14

First, enable the cycle counter once at startup:

CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CYCCNT = 0;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;

then, you can access its value:

unsigned long t1 = DWT->CYCCNT;
/* do something */
unsigned long t2 = DWT->CYCCNT;
unsigned long diff = t2 - t1;

It counts the elapsed cpu cycles, you have to divide it with the cpu clock frequency to get a value in seconds.

As it's a 32 bit value, it can overflow quite fast at higher clock frequencies, e.g in 19.88 seconds at 216 MHz.

4

If you've got HAL available try;

int millis = HAL_GetTick();
SolwiseMD
  • 69
  • 5