androidandroid-ndkgettimeofday

why NDK GetCurrentTime incorrect?


I use the following code

unsigned long long appUtils::GetCurrentTime() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

This code runs on the OSX platform. After clang is compiled, the output is 1618460301601. This result is correct I am under NDK ,r17c r21d

unsigned long long  xx = appUtils::GetCurrentTime();
LOGD("app current time: %u %llu %lld", xx, xx, xx);
// OUTPUT app current time: 3553827972 15263574918903831684 6951239348438933920

However, I use NDK to compile and run on the emulator or mobile phone, and I will get this value 3553827972 How do I get the current time


Solution

  • %u is the wrong format specifier to use, since it corresponds to unsigned int, which on all relevant platforms is a 32-bit type. The value 1618460301601 requires at lest 64 bits, so you need to use %llu or %lld.

    If you built your code for a 32-bit ABI (e.g. armeabi-v7a or x86) then using that incorrect %u specifier for the first argument will also mess up the printing of the other arguments, due to how printf-like function process their integer arguments.