c++

gettimeofday在C++中如何精确使用

小樊
99
2024-07-14 16:49:29
栏目: 编程语言

在C++中,可以使用gettimeofday函数来获取当前时间精确到微秒级别。该函数在sys/time.h头文件中定义,可以通过以下代码使用:

#include <iostream>
#include <sys/time.h>

int main() {
    timeval currentTime;
    gettimeofday(&currentTime, NULL);

    unsigned long long milliseconds = currentTime.tv_sec * 1000 + currentTime.tv_usec / 1000;
    unsigned long long microseconds = currentTime.tv_sec * 1000000 + currentTime.tv_usec;

    std::cout << "Milliseconds: " << milliseconds << std::endl;
    std::cout << "Microseconds: " << microseconds << std::endl;

    return 0;
}

在上面的示例中,首先声明一个timeval结构体变量currentTime来存储当前时间,然后调用gettimeofday函数来获取当前时间。tv_sec成员变量表示秒数,tv_usec成员变量表示微秒数。可以根据需要将秒数和微秒数转换成毫秒或微秒表示。

0
看了该问题的人还看了