如何在STM32上获得时间间隔? [英] How to get time intervals on STM32?
问题描述
我想测量单个函数在 STM32 上需要多长时间.我唯一能找到的是SysTick_Handler
.但是,这是一个周期性中断,但我需要的是获取时间间隔,如:
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);
我尝试过 C clock()
,但它不起作用并且总是返回 -1
.我该怎么做?
I've tried C clock()
, but it didn't work and always return -1
. How can I make it?
推荐答案
首先,在启动时启用一次循环计数器:
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;
它计算经过的 cpu 周期,您必须将其除以 cpu 时钟频率才能获得以秒为单位的值.
It counts the elapsed cpu cycles, you have to divide it with the cpu clock frequency to get a value in seconds.
因为它是一个 32 位值,所以它可以在更高的时钟频率下非常快地溢出,例如在 216 MHz 时为 19.88 秒.
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.
这篇关于如何在STM32上获得时间间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!