简体   繁体   English

如何在C ++中以微秒为单位获取系统时钟?

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

I am working on a project using Visual C++ /CLR in console mode. 我正在控制台模式下使用Visual C ++ / CLR进行项目。 How can I get the system clock in microseconds ? 如何获得以微秒为单位的系统时钟? I want to display hours:minutes:seconds:microseconds 我想显示hours:minutes:seconds:microseconds

The following program works well but is not compatible with other platforms: 以下程序运行良好,但与其他平台不兼容:

#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;
}

You could use ptime microsec_clock::local_time() from Boost. 您可以使用Boost中的ptime microsec_clock::local_time()

The documentation is available here . 该文档可在此处获得

After that, you can use std::string to_iso_extended_string(ptime) to display the returned time as a string or you can use the members of ptime directly to format the output by yourself. 之后,您可以使用std::string to_iso_extended_string(ptime)将返回的时间显示为字符串,也可以直接使用ptime的成员ptime设置输出格式。

Anyway it is worth noting that: 无论如何,值得注意的是:

Win32 systems often do not achieve microsecond resolution via this API. Win32系统通常无法通过此API达到微秒级的分辨率。 If higher resolution is critical to your application test your platform to see the achieved resolution. 如果更高的分辨率对您的应用程序至关重要,请测试平台以查看达到的分辨率。

So I guess it depends on how precise you require your "clock" to be. 因此,我想这取决于您需要的“时钟”精确度。

thank you Mr ereOn 谢谢你,先生

I followed your instructions and i have wrote this code ==> it works 100 % 我按照您的指示进行了操作,我已经写了这段代码==>它可以正常工作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