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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With