pico-sdk icon indicating copy to clipboard operation
pico-sdk copied to clipboard

Time measured with <chrono> returns random/bogus results

Open Rickbude opened this issue 1 year ago • 1 comments

Hi there,

I am trying to measure time elapsed in my code using std::chrono. The code compiles just fine, but the time measurements seem to be completely random. I tried all of system_clock, steady_clock and high_resolution_clock. I know I could just use time_us_64() or similar, but if possible I would like to stick to "standard" C++ as much as possible.

In my CMakeLists, I have tried linking with pico_stdlib, pico_time and hardware_rtc. Below is a code example.

#include <iostream>
#include <chrono>
#include "pico/stdlib.h"

//Which of these are needed?
#include "hardware/rtc.h"
#include "pico/util/datetime.h"
#include <sys/time.h>
 
long fibonacci(unsigned n)
{
    if (n < 2) return n;
    return fibonacci(n-1) + fibonacci(n-2);
}
 
int main()
{
    //Enable output
    stdio_init_all();

    // Start the RTC. Is this needed?
    rtc_init();

    while(1)
    {
        auto start = std::chrono::system_clock::now();
        std::cout << "f(30) = " << fibonacci(30) << '\n';
        auto end = std::chrono::system_clock::now();
        std::chrono::duration<double> elapsed_seconds = end-start;
        std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";
    }   
}

Again, this compiles just fine, but it prints:

f(30) = 832040
elapsed time: 0.00000s
f(30) = 832040
elapsed time: 0.00000s
f(30) = 832040
elapsed time: 8.03131e+08s
f(30) = 832040
elapsed time: 1.55425e+09s
f(30) = 832040
elapsed time: -2.35739e+09s
f(30) = 832040
elapsed time: 3.70503e+09s
f(30) = 832040
elapsed time: -1.98570e+09s

Am I missing something here? Is this perhaps related to issue #93?

Rickbude avatar Sep 25 '22 21:09 Rickbude

See also #27

for now, you can implement int _gettimeofday (struct timeval *__restrict __p, void *__restrict __tz) yourself.

I think this is more useful to implement now in the SDK since we have added Wi-Fi support as you can reasonably get the current time. Therefore we should provide a way to relate the time_us64() to the epoch also.

kilograham avatar Sep 25 '22 22:09 kilograham

fixed by #1186

kilograham avatar Jan 23 '23 20:01 kilograham

merged into develop

kilograham avatar Jan 24 '23 15:01 kilograham