1

我正在开发一个在控制台模式下使用 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;
}
4

2 回答 2

1

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

文档可在此处获得。

之后,您可以使用std::string to_iso_extended_string(ptime)将返回的时间显示为字符串,也可以ptime直接使用 的成员自行格式化输出。

无论如何,值得注意的是:

Win32 系统通常无法通过此 API 实现微秒级分辨率。如果更高的分辨率对您的应用程序至关重要,请测试您的平台以查看达到的分辨率。

所以我想这取决于你要求你的“时钟”有多精确。

于 2012-04-30T11:34:42.407 回答
0

谢谢ereOn先生

我按照您的指示编写了此代码 ==> 它 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;
}
于 2012-05-01T21:13:04.870 回答