以毫秒为单位捕获时间

时间:2009-07-13 16:16:14

标签: c++ stl timer resolution

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

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

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

7 个答案:

答案 0 :(得分:20)

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

在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为您执行此操作:)

答案 1 :(得分:16)

// 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;

答案 2 :(得分:4)

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

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

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

答案 3 :(得分:2)

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

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

答案 4 :(得分:2)

如果您不想使用任何特定于操作系统的代码,则可以使用为大多数标准操作系统提供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支持此操作系统)。

答案 5 :(得分:1)

在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

答案 6 :(得分:1)

使用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<milliseconds>(),您将自动获得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
相关问题