Get a timestamp in C in microseconds? Get a timestamp in C in microseconds? c c

Get a timestamp in C in microseconds?


You need to add in the seconds, too:

unsigned long time_in_micros = 1000000 * tv.tv_sec + tv.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).


You have two choices for getting a microsecond timestamp. The first (and best) choice, is to use the timeval type directly:

struct timeval GetTimeStamp() {    struct timeval tv;    gettimeofday(&tv,NULL);    return tv;}

The second, and for me less desirable, choice is to build a uint64_t out of a timeval:

uint64_t GetTimeStamp() {    struct timeval tv;    gettimeofday(&tv,NULL);    return tv.tv_sec*(uint64_t)1000000+tv.tv_usec;}


struct timeval contains two components, the second and the microsecond. A timestamp with microsecond precision is represented as seconds since the epoch stored in the tv_sec field and the fractional microseconds in tv_usec. Thus you cannot just ignore tv_sec and expect sensible results.

If you use Linux or *BSD, you can use timersub() to subtract two struct timeval values, which might be what you want.