Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current time in milliseconds from C in Linux?

Tags:

c

linux

posix

How do I get the current time on Linux in milliseconds?

like image 845
LLL Avatar asked Sep 20 '10 23:09

LLL


People also ask

How to get time in milliseconds in c Linux?

Use gettimeofday() to get the time in seconds and microseconds.

How do you find time in milliseconds?

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.

Can Time_t store 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.


1 Answers

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.

like image 175
Dan Moulding Avatar answered Sep 20 '22 05:09

Dan Moulding