Following is the util function to get current timestamp in milliseconds:
#include <sys/time.h>
long long current_timestamp() {
struct timeval te;
gettimeofday(&te, NULL); // get current time
long long milliseconds = te.tv_sec*1000LL + te.tv_usec/1000; // calculate milliseconds
// printf("milliseconds: %lld\n", milliseconds);
return milliseconds;
}
About timezone:
gettimeofday() support to specify timezone,
I use NULL, which ignore the timezone, but you can specify a timezone, if need.
@Update - timezone
Since the long representation of time is not relevant to or effected by timezone itself, so setting tz param of gettimeofday() is not necessary, since it won't make any difference.
And, according to man page of gettimeofday(), the use of the timezone structure is obsolete, thus the tz argument should normally be specified as NULL, for details please check the man page.
In the current version of POSIX, gettimeofday is marked obsolete. This means it may be removed from a future version of the specification. Application writers are encouraged to use the clock_gettime function instead of gettimeofday.
Here is an example of how to use clock_gettime:
#define _POSIX_C_SOURCE 200809L
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
void print_current_time_with_ms (void)
{
long ms; // Milliseconds
time_t s; // Seconds
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
s = spec.tv_sec;
ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds
if (ms > 999) {
s++;
ms = 0;
}
printf("Current time: %"PRIdMAX".%03ld seconds since the Epoch\n",
(intmax_t)s, ms);
}
If your goal is to measure elapsed time, and your system supports the "monotonic clock" option, then you should consider using CLOCK_MONOTONIC instead of CLOCK_REALTIME.
Jirka Justra's answer returns a long, which is usually 32 bits. The number of milliseconds since unix time 0 in 1970 requires more bits, so the data type
should be long long or unsigned long long, which is usually 64 bits. Also, as Kevin Thibedeau commented, rounding can be done without converting to floating point or using math.h.
#include <time.h>
long long millis () {
struct timespec t ;
clock_gettime ( CLOCK_REALTIME , & t ) ;
return t.tv_sec * 1000 + ( t.tv_nsec + 500000 ) / 1000000 ;
}
If you are trying to measure time less than 50 days, 32 bits is enough. Data type int is 32 bits or 64 bits on most computers, so the data type can be unsigned int.