我需要获取我使用 NDK/JNI 在 C 中实现的算法的某些部分的计算时间。
我读过这个问题:Android Get Current timestamp?
我想我可以通过这种方式使用相同的方法获取 JNI 调用的计算时间:
Long start, end, time;
start = System.currentTimeMillis()/1000;
//my native call
end = System.currentTimeMillis()/1000;
time = end - start;
Log.i(TAG, "Time ... (ms): " + time);
但是我需要检查native方法中一些小部分的计算时间。我该怎么做?
最佳答案
最好不要在移动设备上使用 gettimeofday()
或 currentTimeMillis()
。这些返回“挂钟”时间,如果网络更新时间,它可以突然向前或向后跳跃。
使用单调时钟代替性能测量 -- System.nanoTime
() 或 clock_gettime()
with CLOCK_MONOTONIC
。请注意,这会返回一个 struct timespec
而不是 struct timeval
;主要区别在于时钟分辨率是纳秒而不是微秒。
int64_t getTimeNsec() {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return (int64_t) now.tv_sec*1000000000LL + now.tv_nsec;
}
除了挂钟时间,您可能还对每线程 CPU 时间感兴趣;见Thread Performance in Android .
关于android - NDK中如何获取计算时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17188761/