代码之家  ›  专栏  ›  技术社区  ›  Pandoro

如何在原生Android代码中获取当前时间?

  •  22
  • Pandoro  · 技术社区  · 15 年前

    提前谢谢!

    3 回复  |  直到 15 年前
        1
  •  17
  •   fadden    8 年前

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

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

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

    这两个都是posixapi,而不是特定于Android的。

        2
  •  31
  •   torger    13 年前

    #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
    
        3
  •  5
  •   donturner    9 年前

    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;
    }
    
    推荐文章