How do I get the current time on Linux in milliseconds?
问题:
回答1:
This can be achieved using the clock_gettime
function.
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 #include #include #include 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
.
回答2:
You have to do something like this:
struct timeval tv; gettimeofday(&tv, NULL); double time_in_mill = (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ; // convert tv_sec & tv_usec to millisecond
回答3:
Following is the util function to get current timestamp in milliseconds:
#include 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.
回答4:
Use gettimeofday()
to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.
回答5:
C11 timespec_get
It returns up to nanoseconds, rounded to the resolution of the implementation.
It is already implemented in Ubuntu 15.10. API looks the same as the POSIX clock_gettime
.
#include struct timespec ts; timespec_get(&ts, TIME_UTC); struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ };
More details here: https://stackoverflow.com/a/36095407/895245
回答6:
If you're looking for something to type into your command line, then date +%H:%M:%S.%N
will give you the time with nanoseconds.