如何在NDK中获得计算时间

时间:2013-06-19 10:19:34

标签: android performance time android-ndk java-native-interface

我需要获得我在C中用NDK / JNI实现的算法的某些部分的计算时间。

我读过这个问题: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);

但是我需要检查本机方法中一些小部件的计算时间。我该怎么办?

2 个答案:

答案 0 :(得分:14)

最好不要在移动设备上使用gettimeofday()currentTimeMillis()。这些返回“挂钟”时间,如果网络更新时间,它可以突然向前或向后跳跃。

使用单调时钟代替性能测量 - System.nanoTime()或clock_gettime() 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

答案 1 :(得分:7)

从您的C / C ++代码中

#include <sys/time.h>
long long currentTimeInMilliseconds()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return ((tv.tv_sec * 1000) + (tv.tv_usec / 1000));
}

这将为您提供一个结构,其当前时间以秒和微秒为单位,足以让您足够轻松地测量两点之间的时间。然后它执行转换以返回当前时间,以毫秒为单位。

编辑:根据@ ChrisStratton的建议更新。