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
Release: 2024-11-15 17:47:03
Original
840 people have browsed it

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>
    Copy after login
  2. Define a struct timeval to store the seconds and microseconds:

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

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

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

    gettimeofday(&end, NULL);
    Copy after login
  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;
    Copy after login
  7. Print the elapsed time in milliseconds:

    printf("Elapsed time: %ld milliseconds\n", mtime);
    Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template