Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current time in native Android code?

Tags:

I was wondering if there is an easy way to get the current time in native Android code. Optimally it would be something comparable to System.getTimeMillies(). I will only be using it to see how long certain function calls will take so a long variable with the current time in milliseconds would be the optimal solution for me.

Thanks in advance!

like image 384
Pandoro Avatar asked Sep 30 '10 15:09

Pandoro


2 Answers

For the lazy, add this to the top of your code:

#include <time.h>  // from android samples /* return current time in milliseconds */ static double now_ms(void) {      struct timespec res;     clock_gettime(CLOCK_REALTIME, &res);     return 1000.0 * res.tv_sec + (double) res.tv_nsec / 1e6;  } 

Call it like this:

double start = now_ms(); // start time  // YOUR CODE HERE  double end = now_ms(); // finish time  double delta = end - start; // time your code took to exec in ms 
like image 97
torger Avatar answered Oct 15 '22 17:10

torger


For microsecond resolution you can use gettimeofday(). This uses "wall clock time", which continues to advance when the device is asleep, but is subject to sudden shifts forward or backward if the network updates the device's clock.

You can also use clock_gettime(CLOCK_MONOTONIC). This uses the monotonic clock, which never leaps forward or backward, but stops counting when the device sleeps.

The actual resolution of the timers is device-dependent.

Both of these are POSIX APIs, not Android-specific.

like image 20
fadden Avatar answered Oct 15 '22 17:10

fadden