【问题标题】:How to get the current time in native Android code?如何在原生 Android 代码中获取当前时间?
【发布时间】:2011-04-19 10:15:03
【问题描述】:

我想知道是否有一种简单的方法可以在原生 Android 代码中获取当前时间。最理想的情况是它可以与 System.getTimeMillies() 相媲美。我只会使用它来查看某些函数调用需要多长时间,因此以毫秒为单位的当前时间的长变量对我来说是最佳解决方案。

提前致谢!

【问题讨论】:

    标签: android-ndk


    【解决方案1】:

    对于微秒分辨率,您可以使用gettimeofday()。这使用“挂钟时间”,当设备处于睡眠状态时会继续前进,但如果网络更新设备的时钟,则会突然向前或向后移动。

    您也可以使用clock_gettime(CLOCK_MONOTONIC)。这使用了单调时钟,它从不向前或向后跳跃,而是在设备休眠时停止计数。

    计时器的实际分辨率取决于设备。

    这两个都是 POSIX API,不是 Android 特定的。

    【讨论】:

    • CLOCK_BOOTTIME(从 Linux 2.6.39 开始;特定于 Linux)会更好吗?
    【解决方案2】:

    另一个懒人,这个函数使用CLOCK_MONOTONIC返回当前时间(以纳秒为单位)

    #include <time.h>
    #define NANOS_IN_SECOND 1000000000
    
    static long currentTimeInNanos() {
    
        struct timespec res;
        clock_gettime(CLOCK_MONOTONIC, &res);
        return (res.tv_sec * NANOS_IN_SECOND) + res.tv_nsec;
    }
    

    【讨论】:

    • 我不相信单调时钟可以保证从任何特定值开始,并且依赖long 的大小是不明智的。如果您要将 time_t 乘以 1e9,则应使用显式 64 位类型(例如 int64_t)将 tv_sec 转换为返回值。
    【解决方案3】:

    对于懒惰的人,请将其添加到代码的顶部:

    #include <time.h>
    
    // from android samples
    /* return current time in milliseconds */
    static double now_ms(void) {
    
        struct timespec res;
        clock_gettime(CLOCK_REALTIME, &res);
        return 1000.0 * res.tv_sec + (double) res.tv_nsec / 1e6;
    
    }
    

    这样称呼它:

    double start = now_ms(); // start time
    
    // YOUR CODE HERE
    
    double end = now_ms(); // finish time
    
    double delta = end - start; // time your code took to exec in ms
    

    【讨论】:

    • 请记住CLOCK_REALTIME 不是单调的,如果您需要非递减时间,请使用CLOCK_MONOTONIC。
    猜你喜欢
    • 2015-04-20
    • 2017-02-15
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    • 2011-12-26
    相关资源
    最近更新 更多