2

Is there any known problem with using time(NULL) on Android?

I tried running the following piece of code:

int32_t now1 = time(NULL);
int64_t now1_6 = (int64_t)time(NULL);
int32_t nt = (time_t)-1;
int64_t nt6 = (int64_t)-1;

And then log the result using the following format:

"Now1 is %d. Now1_6 is %lld. NT is %d. NT6 is %lld.\n", now1, now1_6, nt, nt6

This is the output I got:

01-05 19:10:15.354: I/SMOS(11738): Now1 is 1533390320. Now1_6 is 6585861276402981128. NT is 0. NT6 is 283493768396.

There were other problems as well, such as getting the same time values on different loop iterations.

I encountered these issues on both a virtual and a physical device running Android 4.0.3 (API 15), both of which were configured with the correct time. The output above is from the physical device.

I am led to believe there is a problem with this particular POSIX function in Bionic, but I could not find any reference to such, either online or in the Bionic docs.

mcmlxxxvi
  • 1,358
  • 1
  • 11
  • 21
  • 1
    1533390320 is 0x5B65ADF0, which is a reasonable value for time in seconds (albeit somewhat in the future). 6585861276402981128 is 0x5B65ADF000001908, i.e. you've got the 32-bit time in the high part plus some random gunk in the low part. 283493768396 is 0x42018B9CCC, which looks like a 32-bit pointer in the high plus 0xcc000000 in the low. Sounds like something isn't passing args around quite right. Probably not related to time() itself. Tested with `printf()`, I get `Now1 is 1357606954. Now1_6 is 1357606954. NT is -1. NT6 is -1.` – fadden Jan 08 '13 at 00:58
  • You're correct about argument passing - I was mixing log printing functions - `__android_log_print` and `__android_log_vprint` if I remember correctly - so that I was printing garbage to log. If you put up your comment as an answer, I'll accept it. – mcmlxxxvi Mar 02 '16 at 12:00

1 Answers1

1

You are trying to cast an int64_t into a long long, and they might not be equivalent on Android. If you want to print out int64_t values using printf and %lld, either convert the number first to long long, or use the correct format modifier:

printf("%lld", (long long)now1_6);

or

printf("%" PRId64, now1_6);

For the time(NULL) giving false times, try using gettimeofday instead:

struct timeval tm;
gettimeofday( &tm, NULL);
SztupY
  • 10,291
  • 8
  • 64
  • 87
  • Thanks, I didn't know about [these modifiers](http://en.cppreference.com/w/cpp/types/integer). But my problem was mixing log printing functions - `__android_log_print` and `__android_log_vprint` if I remember correctly - so that I was printing garbage to log. – mcmlxxxvi Mar 02 '16 at 11:50