How do I get the current time on Linux in milliseconds?
Use gettimeofday() to get the time in seconds and microseconds.
To get the current time in milliseconds, you just need to convert the output of Sys. time to numeric, and multiply by 1000. Depending on the API call you want to make, you might need to remove the fractional milliseconds.
Use the time() Function to Get Time in Milliseconds in C++time takes an optional argument of type time_t* , where the returned time value is stored. Alternatively, we can use the function return value to store in the separately declared variable. In the latter case, you may pass nullptr as the argument.
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 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With