Obtaining Milliseconds Time on Linux Without Third-Party Libraries
In contrast to Windows, where the clock() function provides milliseconds time, on Linux, it rounds it to the nearest 1000. This limits the precision to the second level, rendering it unusable for capturing milliseconds.
While Qt provides a solution with its QTime class, a more generic approach is sought. By leveraging the standard C library, a reliable method can be employed to obtain milliseconds time on Linux.
The following code snippet demonstrates how to achieve this using the gettimeofday() function:
#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); 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; }
By utilizing the gettimeofday() function, the code retrieves the current time before and after a specified delay (2 milliseconds in this example). The difference in seconds and microseconds is then calculated and converted into milliseconds. This approach provides a precise and standard-compliant method for obtaining milliseconds time on Linux without relying on third-party libraries.
The above is the detailed content of How Can You Get Milliseconds Time on Linux Without Third-Party Libraries?. For more information, please follow other related articles on the PHP Chinese website!