The only thing I know is time(NULL)
, but it return seconds since 1970.
It's fine to me to use WinApi functions if C doesn't have needed function.
I even found GetLocalTime
WinApi function, but it return current date-time as struct...
The reason I don't want to multiply seconds by 1000 is because I inject my code into some program, and my code used to capture certain events from two sources, and I need to know their exact time, because if both events happened at same amount of seconds since 1970, but different amount of milliseconds, then for me they seems like happen in same time, and it's hard to determine what happened first (I doing events sorting later...)
In Unix, you have (probably you'll get some of these apis also working in windows) gettimeofday(2)
, which is BSD implementation of time, it is based on struct timeval
which is a struct
that has two fields, tv_sec
(time in seconds since epoch, as given by time(2)
) and tv_usec
(time in µsec, as an integer, between 0
and 999999
)
This will suffice for your requirements, but today, it is common to use Posix' calls clock_gettime(2)
, which allow you to select the type of time you want to get (wall clock time, cpu time, etc.) clock_gettime(2)
uses a similar struct timespec
(this time it has tv_sec
and tv_nsec
---nanosecond--- resolution)
No clock is warranted to get nanosecond resolution (but someones do), but at least you get up to the µsec level, which is more than you want)
In order to be able to give the time as milliseconds, you have just to multiply the tv_sec
by 1000
, and then add the tv_usec
(if using gettimeofday()
) value divided by 1000
. Or if you prefer to use clock_gettime()
, you will add the tv_sec
field multiplied by 1000
, and then add the tv_nsec
field divided by 1000000
.
If you just need to compare which timestamp is earlier than other, you can just compare both tv_sec
fields, and if they happen to be equal, then compare the tv_usec
fields. Every unix I know about (except SCO UNIX) do implement gettimeofday()
to µsec resolution.