Home  >  Article  >  Backend Development  >  How to Achieve Millisecond Precision Timing in C on Linux Without Relying on clock()?

How to Achieve Millisecond Precision Timing in C on Linux Without Relying on clock()?

Barbara Streisand
Barbara StreisandOriginal
2024-11-13 12:15:02350browse

 How to Achieve Millisecond Precision Timing in C   on Linux Without Relying on clock()?

C : How to Obtain Milliseconds on Linux Without Clock() Limitations

Unlike Windows where clock() returns milliseconds, Linux's implementation rounds the result to the nearest 1000, resulting in second-level precision only. The need for millisecond-level timing prompts the question: Is there a standard C solution without using third-party libraries?

The Answer: gettimeofday()

The answer lies in the standard POSIX function gettimeofday(). This function provides high-precision timing information by populating a timeval structure with the current time. Here's a C example employing gettimeofday():

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

This code demonstrates how to calculate the elapsed time in milliseconds by combining the seconds and microseconds components obtained from gettimeofday(). Note that the 0.5 addition is applied to round the result to the nearest integer.

The above is the detailed content of How to Achieve Millisecond Precision Timing in C on Linux Without Relying on clock()?. 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