While-loop speed enhancement?

salbdch
Posts: 17
Joined: Wed Dec 02, 2020 2:06 pm

While-loop speed enhancement?

Postby salbdch » Wed Feb 10, 2021 5:36 am

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,

ESP_Angus
Posts: 2344
Joined: Sun May 08, 2016 4:11 am

Re: While-loop speed enhancement?

Postby ESP_Angus » Wed Feb 10, 2021 5:55 am

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.

OllieK
Posts: 58
Joined: Mon Jan 18, 2016 8:08 am
Location: USA, PA
Contact:

Re: While-loop speed enhancement?

Postby OllieK » Wed Feb 10, 2021 11:09 pm

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.

Who is online

Users browsing this forum: Baidu [Spider] and 261 guests