Home > Backend Development > C++ > body text

How Can You Get Milliseconds Time on Linux Without Third-Party Libraries?

Barbara Streisand
Release: 2024-11-21 06:20:10
Original
262 people have browsed it

How Can You Get Milliseconds Time on Linux Without Third-Party Libraries?

Obtaining Milliseconds Time on Linux Without Third-Party Libraries

In contrast to Windows, where the clock() function provides milliseconds time, on Linux, it rounds it to the nearest 1000. This limits the precision to the second level, rendering it unusable for capturing milliseconds.

While Qt provides a solution with its QTime class, a more generic approach is sought. By leveraging the standard C library, a reliable method can be employed to obtain milliseconds time on Linux.

The following code snippet demonstrates how to achieve this using the gettimeofday() function:

#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;
}
Copy after login

By utilizing the gettimeofday() function, the code retrieves the current time before and after a specified delay (2 milliseconds in this example). The difference in seconds and microseconds is then calculated and converted into milliseconds. This approach provides a precise and standard-compliant method for obtaining milliseconds time on Linux without relying on third-party libraries.

The above is the detailed content of How Can You Get Milliseconds Time on Linux Without Third-Party 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template