【问题标题】:Capturing a time in milliseconds以毫秒为单位捕获时间
【发布时间】:2009-07-13 16:16:14
【问题描述】:

以下代码用于打印日志中的时间:

#define PRINTTIME() struct tm  * tmptime;
time_t     tmpGetTime;
time(&tmpGetTime);
tmptime = localtime(&tmpGetTime);
cout << tmptime->tm_mday << "/" <<tmptime->tm_mon+1 << "/" << 1900+tmptime->tm_year << " " << tmptime->tm_hour << ":" << tmptime->tm_min << ":" << tmptime->tm_sec<<">>";

有没有办法为此添加毫秒?

【问题讨论】:

标签: c++ stl timer resolution


【解决方案1】:

要获得毫秒精度,您必须使用特定于您的操作系统的系统调用。

在 Linux 中你可以使用

#include <sys/time.h>

timeval tv;
gettimeofday(&tv, 0);
// then convert struct tv to your needed ms precision

timeval 具有微秒精度。

在 Windows 中,您可以使用:

#include <Windows.h>

SYSTEMTIME st;
GetSystemTime(&st);
// then convert st to your precision needs

当然,你可以使用Boost 为你做这件事:)

【讨论】:

  • 对于 Linux,您应该阅读time(7),并且可能使用clock_gettime(2)
  • 也许您可以为函数提供标头?
【解决方案2】:

//C++11 风格:

cout << "Time in Milliseconds =" << 
 chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now().time_since_epoch()).count() 
 << std::endl;

cout << "Time in MicroSeconds=" << 
 chrono::duration_cast<chrono::microseconds>(chrono::steady_clock::now().time_since_epoch()).count() 
 << std::endl;

【讨论】:

    【解决方案3】:

    您需要一个更高分辨率的计时器才能捕获毫秒。试试这个:

    int cloc = clock();
    //do something that takes a few milliseconds
    cout << (clock() - cloc) << endl;
    

    这当然取决于您的操作系统。

    【讨论】:

    • 嗯,我认为 clock() 返回一个代表时钟单位的clock_t。此外,在 linux 上它没有达到毫秒精度 AFAIK
    • @neuro 在我的 Linux 程序中,我收到了 clock() 的双精度值
    【解决方案4】:

    高分辨率计时器通常是 Linux 风格平台上的 gettimeofday 和 Windows 上的 QueryPerformanceCounter。

    您应该注意,对单个操作的持续时间进行计时(即使使用高分辨率计时器)不会产生准确的结果。有太多的随机因素在起作用。要获得可靠的计时信息,您应该循环运行要计时的任务并计算平均任务时间。对于这种类型的计时,clock() 函数应该足够了。

    【讨论】:

      【解决方案5】:

      如果您不想使用任何特定于操作系统的代码,您可以使用为大多数标准操作系统提供ACE_OS::gettimeofday 功能的ACE 包。 例如:

      ACE_Time_Value startTime = ACE_OS::gettimeofday();
      
      do_something();
      
      ACE_Time_Value endTime = ACE_OS::gettimeofday();
      
      cout << "Elapsed time: " << (endTime.sec() - startTime.sec()) << " seconds and " << double(endTime.usec() - startTime.usec()) / 1000 << " milliseconds." << endl;
      

      无论您的操作系统如何,此代码都可以工作(只要 ACE 支持此操作系统)。

      【讨论】:

        【解决方案6】:

        在 Ubuntu 16.04 中,这对我有用...

        const std::string currentDateTime() {
           char            fmt[64], buf[64];
           struct timeval  tv;
           struct tm       *tm;
        
           gettimeofday(&tv, NULL);
           tm = localtime(&tv.tv_sec);
           strftime(fmt, sizeof fmt, "%Y-%m-%d %H:%M:%S.%%06u", tm);
           snprintf(buf, sizeof buf, fmt, tv.tv_usec);
           return buf;
        }
        

        然后,用...

        std::cout << currentDateTime();
        

        我明白了……

        2016-12-29 11:09:55.331008
        

        【讨论】:

          【解决方案7】:

          使用 C++11 或 C++14 和 free, open-source library 对旧问题的新答案:

          #include "tz.h"
          #include <iostream>
          
          int
          main()
          {
              using namespace date;
              using namespace std;
              using namespace std::chrono;
              auto now = make_zoned(current_zone(), floor<milliseconds>(system_clock::now()));
              cout << format("%e/%m/%Y %T", now) << '\n';
          }
          

          这只是为我输出:

          16/01/2017 15:34:32.167
          

          这是我当前的本地日期和时间,精度为毫秒。通过消除floor&lt;milliseconds&gt;(),您将自动获得system_clock 的精度。

          如果您希望将结果作为 UTC 时间戳而不是本地时间戳,则更简单:

              auto now = floor<milliseconds>(system_clock::now());
              cout << format("%e/%m/%Y %T", now) << '\n';
          

          如果您想要一个 UTC 时间戳并且您对精度或格式不挑剔,您可以:

          cout << system_clock::now() << '\n';
          

          这只是为我输出:

          2017-01-16 20:42:11.267245
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-08-05
            • 2013-05-09
            • 1970-01-01
            • 1970-01-01
            • 2013-05-26
            相关资源
            最近更新 更多