Page 1 of 1

While-loop speed enhancement?

Posted: Wed Feb 10, 2021 5:36 am
by salbdch
Hello,
In my example, while loop in main.c seems working in 1.437ms period
and I need some calculation in us.

Code: Select all

    
    int64_t oldTime, currentTime;
    int16_t deltaTime;

    while(1) {    
        oldTime = currentTime;
        currentTime = esp_timer_get_time(); 
        deltaTime = currentTime - oldTime;
        printf("deltaTime: %d\n", deltaTime); // deltaTime = 1437
        }
Is there any way to enhance while loop speed?
Regards,

Re: While-loop speed enhancement?

Posted: Wed Feb 10, 2021 5:55 am
by ESP_Angus
Hi salbdch,

A while loop by itself is able to run a lot faster than this, the issue here is that you're counting the time to call esp_timer_get_time() and (much more importantly) the time to call printf(), which after the output buffer in RAM fills up includes all the time needed to flush the previous output to the UART port. At 115200bps UART transmitting 16 characters takes (1000 /(115200 / (16*10)) = 1.38 milliseconds. Plus there is some overhead for the time spent formatting the string.

If you need to print on every loop then you could try increasing the baud rate, but the best thing you can do is to minimize the amount of printing you need to do.

Re: While-loop speed enhancement?

Posted: Wed Feb 10, 2021 11:09 pm
by OllieK
For microsecond level time measurements you need timer_u32() function. It is available in

https://github.com/OliviliK/ESP32_timer_u32

There is an example how the measurements are done for a function taking 0.3 - 9.0 microseconds to execute.