Home  >  Article  >  Backend Development  >  How Can I Get Millisecond Time Accuracy in Linux Without External Libraries?

How Can I Get Millisecond Time Accuracy in Linux Without External Libraries?

Linda Hamilton
Linda HamiltonOriginal
2024-11-19 07:05:02572browse

How Can I Get Millisecond Time Accuracy in Linux Without External Libraries?

Acquiring Millisecond Time in Linux: An Alternative to clock()

Seeking precision beyond the bounds of seconds in Linux, we encounter the limitation of clock(), which only approximates to the nearest second. While third-party libraries like Qt provide solutions using the QTime class, aspiring towards a more foundational approach, we explore the realm of standard C tools.

To achieve millisecond accuracy, consider employing the gettimeofday() function from the header. This function returns a timeval structure, capturing the current time with both seconds and microseconds components.

Consider the following code snippet:

#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;
}

In this example, we leverage gettimeofday() to capture the current time before and after a 2-millisecond delay using usleep(). By subtracting the initial time from the final time, we obtain the elapsed time in seconds and microseconds. To convert this to milliseconds, we multiply the seconds by 1000 and the microseconds by 1000.0 and add them together, ensuring fractional accuracy with the 0.5 adjustment.

This method offers a precise and standard solution for obtaining milliseconds in C on Linux, eliminating the reliance on external libraries while maintaining compatibility across various platforms.

The above is the detailed content of How Can I Get Millisecond Time Accuracy in Linux Without External Libraries?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn