Kristina Brooks Kristina Brooks - 10 days ago 5x
C Question

Get a timestamp in C in microseconds?

How do I get a microseconds timestamp in C?

I'm trying to do:

struct timeval tv;
return tv.tv_usec;

But this returns some nonsense value that if I get two timestamps, the second one can be smaller or bigger than the first (second one should always be bigger). Would it be possible to convert the magic integer returned by gettimeofday to a normal number which can actually be worked with?


You need to add in the seconds, too:

unsigned long time_in_micros = 1000000 * tv_sec + tv_usec;

Note that this will only last for about 232/106 =~ 4295 seconds, or roughly 71 minutes though (on a typical 32-bit system).