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

c++
小樊
99
2024-07-14 16:49:29
欄目: 編程語言

在C++中,可以使用gettimeofday函數(shù)來獲取當(dāng)前時(shí)間精確到微秒級(jí)別。該函數(shù)在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;
}

在上面的示例中,首先聲明一個(gè)timeval結(jié)構(gòu)體變量currentTime來存儲(chǔ)當(dāng)前時(shí)間,然后調(diào)用gettimeofday函數(shù)來獲取當(dāng)前時(shí)間。tv_sec成員變量表示秒數(shù),tv_usec成員變量表示微秒數(shù)??梢愿鶕?jù)需要將秒數(shù)和微秒數(shù)轉(zhuǎn)換成毫秒或微秒表示。

0