How do I get the current time on Linux in milliseconds?
相关问题
- Multiple sockets for clients to connect to
- Is shmid returned by shmget() unique across proces
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- how to get running process information in java?
This can be achieved using the POSIX
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 theclock_gettime
function instead ofgettimeofday
.Here is an example of how to use
clock_gettime
:If your goal is to measure elapsed time, and your system supports the "monotonic clock" option, then you should consider using
CLOCK_MONOTONIC
instead ofCLOCK_REALTIME
.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
.More details here: https://stackoverflow.com/a/36095407/895245
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.Following is the util function to get current timestamp in milliseconds:
About timezone:
@Update - timezone
Since the
long
representation of time is not relevant to or effected by timezone itself, so settingtz
param of gettimeofday() is not necessary, since it won't make any difference.And, according to man page of
gettimeofday()
, the use of thetimezone
structure is obsolete, thus thetz
argument should normally be specified as NULL, for details please check the man page.You have to do something like this:
Use
gettimeofday()
to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.