在 Android 上使用 time(NULL)
有什么已知问题吗?
我尝试运行以下代码:
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;
然后使用以下格式记录结果:
"Now1 is %d. Now1_6 is %lld. NT is %d. NT6 is %lld.\n", now1, now1_6, nt, nt6
这是我得到的输出:
01-05 19:10:15.354: I/SMOS(11738): Now1 is 1533390320. Now1_6 is 6585861276402981128. NT is 0. NT6 is 283493768396.
还有其他问题,例如在不同的循环迭代中获得相同的时间值。
我在运行 Android 4.0.3 (API 15) 的虚拟设备和物理设备上都遇到了这些问题,这两个设备都配置了正确的时间。上面的输出来自物理设备。
我被引导相信 Bionic 中的这个特定 POSIX 函数存在问题,但我无法在网上或 Bionic 文档中找到任何相关引用。
最佳答案
您正在尝试将 int64_t
转换为 long long
,它们在 Android 上可能不等价。如果要使用 printf
和 %lld
打印出 int64_t
值,请先将数字转换为 long long
,或使用正确的格式修饰符:
printf("%lld", (long long)now1_6);
或
printf("%" PRId64, now1_6);
对于给出错误时间的 time(NULL)
,尝试使用 gettimeofday
代替:
struct timeval tm;
gettimeofday( &tm, NULL);
关于android - 在 Android 上使用时间(NULL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14174346/