Home >Backend Development >C++ >How to Achieve Milliseconds-Precise Timing in C on Linux Without External Libraries?

How to Achieve Milliseconds-Precise Timing in C on Linux Without External Libraries?

DDD
DDDOriginal
2024-11-15 17:47:03842browse

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:

  1. Include necessary headers:

    #include <sys/time.h>
    #include <stdio.h>
    #include <unistd.h>
  2. Define a struct timeval to store the seconds and microseconds:

    struct timeval start, end;
  3. Get the start time:

    gettimeofday(&start, NULL);
  4. Specify a delay in microseconds using usleep() (replace with your desired delay):

    usleep(2000);
  5. Get the end time:

    gettimeofday(&end, NULL);
  6. 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;
  7. 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!

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