如何在NDK中获得计算时间

Ale*_*tta 11 performance time java-native-interface android android-ndk

我需要获得我在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);
Run Code Online (Sandbox Code Playgroud)

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

fad*_*den 15

最好不要使用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;
}
Run Code Online (Sandbox Code Playgroud)

除了挂钟时间,您可能对每线程CPU时间感兴趣; 请参阅Android中的线程性能.


mah*_*mah 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));
}
Run Code Online (Sandbox Code Playgroud)

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

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