Home > Backend Development > C++ > How to Achieve Millisecond Precision Time Measurement in Linux?

How to Achieve Millisecond Precision Time Measurement in Linux?

DDD
Release: 2024-11-13 10:58:02
Original
915 people have browsed it

How to Achieve Millisecond Precision Time Measurement in Linux?

Obtaining Millisecond Precision Time Measurement in Linux

When working with time measurements in C , the clock() function provides a convenient method to retrieve the current time in milliseconds on Windows systems. However, on Linux, clock() may provide less precise results, rounding the time to the nearest second.

In this case, the solution is to utilize the standard sys/time.h header and functions. The gettimeofday() function returns the current time of day as a timeval struct, which contains both seconds and microseconds since the Epoch. By subtracting the start time from the end time and converting the microseconds into milliseconds, we can obtain millisecond precision time measurements.

Here's an example code snippet that demonstrates how to use gettimeofday() to achieve millisecond precision time measurement:

#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); // Sleep for 2 milliseconds
    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;
}
Copy after login

In this example, gettimeofday() is used to retrieve both the start and end times. The difference between the seconds and microseconds is calculated, and the result is converted into milliseconds with a precision up to 0.5 milliseconds.

The above is the detailed content of How to Achieve Millisecond Precision Time Measurement in Linux?. 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