溫馨提示×

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

c++
小樊
130
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成員變量表示微秒數??梢愿鶕枰獙⒚霐岛臀⒚霐缔D換成毫秒或微秒表示。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女