我想知道是否有一种简单的方法来获取原生Android代码的当前时间.最佳地,它可以与System.getTimeMillies()相媲美.我将只使用它来查看某些函数调用将花费多长时间,所以一个长变量与当前时间(以毫秒为单位)将是我的最佳解决方案.
提前致谢!
tor*_*ger 29
对于懒惰,将其添加到代码的顶部:
#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
fad*_*den 17
对于微秒分辨率,您可以使用gettimeofday().这使用"挂钟时间",它在设备处于睡眠状态时继续前进,但如果网络更新设备的时钟,则会突然向前或向后移动.
你也可以使用clock_gettime(CLOCK_MONOTONIC).这使用单调时钟,它从不向前或向后跳跃,但在设备休眠时停止计数.
定时器的实际分辨率取决于设备.
这两个都是POSIX API,而不是Android特定的.
另一个用于延迟,此函数使用以下命令返回当前时间(以纳秒为单位) 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;
}
| 归档时间: | 
 | 
| 查看次数: | 21261 次 | 
| 最近记录: |