簡體   English   中英

如何在C ++中以微秒為單位獲取系統時鍾?

[英]How to Get system clock in microseconds in C++?

我正在控制台模式下使用Visual C ++ / CLR進行項目。 如何獲得以微秒為單位的系統時鍾? 我想顯示hours:minutes:seconds:microseconds

以下程序運行良好,但與其他平台不兼容:

#include <stdio.h>
#include <sys/time.h>
int main()
{
     struct timeval tv;
     struct timezone tz;
     struct tm *tm;
     gettimeofday(&tv, &tz);
     tm=localtime(&tv.tv_sec);
     printf(" %d:%02d:%02d %ld \n", tm->tm_hour, tm->tm_min,tm->tm_sec, tv.tv_usec);
     return 0;
}

您可以使用Boost中的ptime microsec_clock::local_time()

該文檔可在此處獲得

之后,您可以使用std::string to_iso_extended_string(ptime)將返回的時間顯示為字符串,也可以直接使用ptime的成員ptime設置輸出格式。

無論如何,值得注意的是:

Win32系統通常無法通過此API達到微秒級的分辨率。 如果更高的分辨率對您的應用程序至關重要,請測試平台以查看達到的分辨率。

因此,我想這取決於您需要的“時鍾”精確度。

謝謝你,先生

我按照您的指示進行了操作,我已經寫了這段代碼==>它可以正常工作100%

#include <iostream>
#include "boost/date_time/posix_time/posix_time.hpp" 

typedef boost::posix_time::ptime Time;


int main (){

    int i;
    Time t1;

    for (int i=0;i<1000;i++)
    {

         t1=boost::posix_time::microsec_clock::local_time();
     std::cout << to_iso_extended_string(t1) << "\n";
    }


    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM