Page 1 of 1

gettimeofday not working with timeval [IDFGH-3263]

Posted: Thu May 07, 2020 9:44 am
by halilarkl07
Hi guys,
I have a problem with getting time. I need to get the current time in millisecond resolution.
I know that gettimeofday can get in microsecond resolution based on:
https://docs.espressif.com/projects/esp ... _time.html



I am using;
  1. struct timeval tv_now;
  2.  
  3. gettimeofday(&tv_now, NULL);
  4.  
  5. int64_t time_us = (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec;
  6.  
  7. printf("time_us %" PRId64 "\n", time_us);
time_us 2806483326588896768
after 10 sec;
time_us 2961102149255896768
there is no sense between them,

also "tv_now.tv_usec" always 0 no mether what.
  1. printf("tv_now.tv_sec %" PRId64 "\n", (int64_t)tv_now.tv_usec);




This is the code;
  1. struct timeval tv_now;
  2.  
  3. gettimeofday(&tv_now, NULL);
  4.  
  5. int64_t time_us = (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec;
  6.  
  7. printf("tv_now.tv_sec %ld\n", (long)tv_now.tv_sec);
  8.  
  9. printf("PRId64 tv_now.tv_sec %" PRId64 "\n", (int64_t)tv_now.tv_sec);
  10.  
  11. printf("tv_now.tv_usec %" PRId64 "\n", (int64_t)tv_now.tv_usec);
  12.  
  13. printf("time_us %" PRId64 "\n", time_us);
And this is the serial monitor output for the code above:

tv_now.tv_sec 1588757091
PRId64 tv_now.tv_sec 39854590296675
tv_now.tv_usec 0
time_us 2961102149255896768

I am an amateur with all this,
Thank you all for helping me.

Re: gettimeofday not working with timeval [IDFGH-3263]

Posted: Mon May 11, 2020 6:27 am
by ESP_Alvin
Moderator's note: edit the topic title for issue tracking, thanks.

Re: gettimeofday not working with timeval [IDFGH-3263]

Posted: Mon May 11, 2020 5:54 pm
by Konstantin
Hi @halilarkl07!
I tried your code and can not get the same result as you reported (it works as expected). I used the hello_world example as a base and put your code. I suggest you try my way, apply the hello_world_patch.txt patch for hello_world. The log like this:

tv_now.tv_sec 0
PRId64 tv_now.tv_sec 0
tv_now.tv_usec 38442
time_us 38442
...
tv_now.tv_sec 11
PRId64 tv_now.tv_sec 11
tv_now.tv_usec 374873
time_us 11374873
...
tv_now.tv_sec 22
PRId64 tv_now.tv_sec 22
tv_now.tv_usec 716287
time_us 22716287

Thanks.

Re: gettimeofday not working with timeval [IDFGH-3263]

Posted: Mon May 11, 2020 7:31 pm
by halilarkl07
Problem solved,
  1. #include <sys/param>
Somehow this header cause the problem with timeval.
while this written, tv_sec was long long int, but when I erase the "#include <sys/param>" tv_sec become long int.

Now everything okay,

Thank you for helping me @Konstantin,
Have a great day.