Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain computation time in NDK

I need to obtain the computation time of some parts of an algorithm I have implemented in C with NDK/JNI.

I've read this question: Android Get Current timestamp?

I think I can obtain the computation time of a JNI call using the same method in this way:

Long start, end, time;
start = System.currentTimeMillis()/1000;
//my native call
end = System.currentTimeMillis()/1000;
time = end - start;
Log.i(TAG, "Time ... (ms): " + time);

But I need to check the computation times of some small parts inside the native method. How can I do it?

like image 821
Alessandro Gaietta Avatar asked Jun 19 '13 10:06

Alessandro Gaietta


2 Answers

It's best not to use gettimeofday() or currentTimeMillis() on a mobile device. These return "wall clock" time, which can jump forward or backward suddenly if the network updates the time.

Use the monotonic clock instead for performance measurements -- System.nanoTime() or clock_gettime() with CLOCK_MONOTONIC. Note this returns a struct timespec rather than a struct timeval; primary difference is that the clock resolution is nanoseconds rather than microseconds.

int64_t getTimeNsec() {
    struct timespec now;
    clock_gettime(CLOCK_MONOTONIC, &now);
    return (int64_t) now.tv_sec*1000000000LL + now.tv_nsec;
}

In addition to wall-clock time you may be interested in per-thread CPU time; see Thread Performance in Android.

like image 170
fadden Avatar answered Nov 18 '22 12:11

fadden


From within your C/C++ code,

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

This will get you a structure with the current time in seconds and microseconds, giving you enough to measure time between two points fairly easily. It then performs the conversion to return the current time, in milliseconds.

Edit: updated per @ChrisStratton's suggestion.

like image 7
mah Avatar answered Nov 18 '22 11:11

mah