Home >Backend Development >C++ >How to Achieve Millisecond Precision Time Measurement in Linux?
Obtaining Millisecond Precision Time Measurement in Linux
When working with time measurements in C , the clock() function provides a convenient method to retrieve the current time in milliseconds on Windows systems. However, on Linux, clock() may provide less precise results, rounding the time to the nearest second.
In this case, the solution is to utilize the standard sys/time.h header and functions. The gettimeofday() function returns the current time of day as a timeval struct, which contains both seconds and microseconds since the Epoch. By subtracting the start time from the end time and converting the microseconds into milliseconds, we can obtain millisecond precision time measurements.
Here's an example code snippet that demonstrates how to use gettimeofday() to achieve millisecond precision time measurement:
#include <sys/time.h> #include <stdio.h> #include <unistd.h> int main() { struct timeval start, end; long mtime, seconds, useconds; gettimeofday(&start, NULL); usleep(2000); // Sleep for 2 milliseconds gettimeofday(&end, NULL); seconds = end.tv_sec - start.tv_sec; useconds = end.tv_usec - start.tv_usec; mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5; printf("Elapsed time: %ld milliseconds\n", mtime); return 0; }
In this example, gettimeofday() is used to retrieve both the start and end times. The difference between the seconds and microseconds is calculated, and the result is converted into milliseconds with a precision up to 0.5 milliseconds.
The above is the detailed content of How to Achieve Millisecond Precision Time Measurement in Linux?. For more information, please follow other related articles on the PHP Chinese website!