Programming Tips - C/C++: How to get the current time in milliseconds?

Date: 2015sep4 Update: 2025oct17 OS: Linux Language: C/C++ Q. C/C++: How to get the current time in milliseconds? A. Use gettimeofday() as shown in this full example:
#include <sys/time.h> // For gettimeofday() #include <stddef.h> // For NULL #include <stdio.h> // For printf() #include <time.h> // For time() long currentMillis() { struct timeval tp; gettimeofday(&tp, NULL); return tp.tv_sec * 1000 + tp.tv_usec / 1000; // Convert the seconds to milliseconds by multiplying by 1000 // Convert the microseconds to milliseconds by dividing by 1000 } void main() { long ms = currentMillis(); printf("current ms=%ld\n", ms); // As a check time_t seconds = time(NULL); long ms_to_seconds = ms / 1000; long diff = seconds - ms_to_seconds; if (diff == 0) { printf("seconds == ms_to_seconds\n"); } else { printf("seconds diffs ms_to_seconds by %ld seconds\n", diff); } }
Output (at one time):
current ms=1760716010082 seconds == ms_to_seconds