Home > Article > Backend Development > How to Achieve Milliseconds-Precise Timing in C on Linux Without External Libraries?
Milliseconds-Precise Timing in C on Linux
Originally asking about why clock() returns time in milliseconds on Windows but only seconds on Linux, the questioner seeks a solution for obtaining millisecond-level time accuracy without relying on third-party libraries like Boost or Qt.
Solution Using gettimeofday()
The solution lies in leveraging the gettimeofday() function present in the standard C library. Here's how to implement it:
Include necessary headers:
#include <sys/time.h> #include <stdio.h> #include <unistd.h>
Define a struct timeval to store the seconds and microseconds:
struct timeval start, end;
Get the start time:
gettimeofday(&start, NULL);
Specify a delay in microseconds using usleep() (replace with your desired delay):
usleep(2000);
Get the end time:
gettimeofday(&end, NULL);
Calculate the elapsed time:
long mtime, seconds, useconds; seconds = end.tv_sec - start.tv_sec; useconds = end.tv_usec - start.tv_usec; mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
Print the elapsed time in milliseconds:
printf("Elapsed time: %ld milliseconds\n", mtime);
This code snippet utilizes gettimeofday() to obtain the time in microseconds, ensuring millisecond-level precision. It serves as a robust and standard solution for acquiring accurate time measurements in C on Linux.
The above is the detailed content of How to Achieve Milliseconds-Precise Timing in C on Linux Without External Libraries?. For more information, please follow other related articles on the PHP Chinese website!