【问题标题】:Get millisecond part of time获取毫秒部分时间
【发布时间】:2012-05-18 14:13:56
【问题描述】:

我需要从计时器获取毫秒数

    // get timer part
    time_t timer = time(NULL);
    struct tm now = *localtime( &timer );
    char timestamp[256];

    // format date time
    strftime(timestamp, sizeof(timestamp), "%Y-%m-%d_%H.%M.%S", &now);

我想在 C# 中变成这样:

DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss.ff")

我尝试使用 %f 或 %F 但它确实适用于 C++。如何从 tm 获得毫秒的 %f?

【问题讨论】:

  • time() 返回自纪元以来的 integer 秒数。因此显然你不能通过使用它来获得亚秒级的精度。请改用gettimeofday()
  • 这需要仅在 Windows 上工作还是跨平台?
  • 对于 unix,请查看我借来的 class,我在 SO 上发布到另一个答案。您可以将其拆解以获取毫秒数。

标签: c++


【解决方案1】:
#include <chrono>

typedef std::chrono::system_clock Clock;

auto now = Clock::now();
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
auto fraction = now - seconds;
time_t cnow = Clock::to_time_t(now);

然后您可以以秒精度打印 time_t,然后打印分数代表的任何内容。可能是毫秒、微秒或其他。具体获取毫秒数:

auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(fraction);
std::cout << milliseconds.count() << '\n';

【讨论】:

  • 这是 C++11 方法
  • 据我所知,您不能直接将duration_cast 应用于时间点。
  • @KyleStrand 你是对的。我已经发布了更正。
  • 对此进行了深入研究,我认为您正在寻找的是time_point_cast
【解决方案2】:

有函数gettimeofday()。以毫秒为单位返回时间 在这里查看:http://souptonuts.sourceforge.net/code/gettimeofday.c.html

【讨论】:

  • 截至 2018-05-16 链接正常。显示的代码有严重缺陷。它由4个标题和int main(void) { char buffer[30]; struct timeval tv; time_t curtime; gettimeofday(&amp;tv, NULL); curtime=tv.tv_sec; strftime(buffer,30,"%m-%d-%Y %T.",localtime(&amp;curtime)); printf("%s%ld\n",buffer,tv.tv_usec); return 0; }组成——使用%ld格式化微秒(a)不符合问题的格式化毫秒目标和(b)不能准确打印微秒。当tv_usec 保持101 微秒时,它会打印.101 而不是.000101。 — printf("%s%.3ld\n", buffer, tv.tv_usec / 1000);
【解决方案3】:

在使用 Win32 API 的 Windows 上 SYSTEMTIME structure 会给你毫秒。然后,您应该使用Time Functions 来获取时间。 像这样:

#include <windows.h>

int main()
{
    SYSTEMTIME stime;
    //structure to store system time (in usual time format)
    FILETIME ltime;
    //structure to store local time (local time in 64 bits)
    FILETIME ftTimeStamp;
    char TimeStamp[256];//to store TimeStamp information
    GetSystemTimeAsFileTime(&ftTimeStamp); //Gets the current system time

    FileTimeToLocalFileTime (&ftTimeStamp,&ltime);//convert in local time and store in ltime
    FileTimeToSystemTime(&ltime,&stime);//convert in system time and store in stime

    sprintf(TimeStamp, "%d:%d:%d:%d, %d.%d.%d",stime.wHour,stime.wMinute,stime.wSecond, 
            stime.wMilliseconds, stime.wDay,stime.wMonth,stime.wYear);

    printf(TimeStamp);

    return 0;
} 

【讨论】:

    【解决方案4】:

    这是另一个 c++11 答案:

    #include <iostream>
    #include <iomanip>
    #include <chrono>
    #ifdef WIN32
    #define localtime_r(_Time, _Tm) localtime_s(_Tm, _Time)
    #endif
    
    int main()
    {
        tm localTime;
        std::chrono::system_clock::time_point t = std::chrono::system_clock::now();
        time_t now = std::chrono::system_clock::to_time_t(t);
        localtime_r(&now, &localTime);
    
        const std::chrono::duration<double> tse = t.time_since_epoch();
        std::chrono::seconds::rep milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(tse).count() % 1000;
    
        std::cout << (1900 + localTime.tm_year) << '-'
            << std::setfill('0') << std::setw(2) << (localTime.tm_mon + 1) << '-'
            << std::setfill('0') << std::setw(2) << localTime.tm_mday << ' '
            << std::setfill('0') << std::setw(2) << localTime.tm_hour << ':'
            << std::setfill('0') << std::setw(2) << localTime.tm_min << ':'
            << std::setfill('0') << std::setw(2) << localTime.tm_sec << '.'
            << std::setfill('0') << std::setw(3) << milliseconds
            << std::endl;
    }
    

    【讨论】:

      【解决方案5】:

      您可以使用boost::posix_time::ptime 上课。 它的reference there

      【讨论】:

      • 我不想因为使用计时器而获得boost库的依赖
      【解决方案6】:

      我个人使用这个:http://wyw.dcweb.cn/time.htm

      【讨论】:

        【解决方案7】:

        在 MS Visual Studio c/c++ 下包含 sys/timeb.h 并使用 _ftime (_ftime_s)。 检索包含 time_t 结构和毫秒的结构 _timeb (_ftime64),请参阅 MSDN http://msdn.microsoft.com/en-/library/z54t9z5f.aspx

        #include <sys/timeb.h>
        
        struct _timeb timebuffer;
        _ftime(&timebuffer);
        timebuffer.millitm; //milli seconds
        timebuffer.time; //the same like struct time_t
        

        【讨论】:

          【解决方案8】:

          试试这个代码:

          struct tvTime;
          
          gettimeofday(&tvTime, NULL);
          
          int iTotal_seconds = tvTime.tv_sec;
          struct tm *ptm = localtime((const time_t *) & iTotal_seconds);
          
          int iHour = ptm->tm_hour;;
          int iMinute = ptm->tm_min;
          int iSecond = ptm->tm_sec;
          int iMilliSec = tvTime.tv_usec / 1000;
          int iMicroSec = tvTime.tv_usec;
          

          【讨论】:

          • 此代码无法编译。您可能指的是struct timeval tvTime;,然后有机会编译。
          猜你喜欢
          • 2012-02-12
          • 1970-01-01
          • 1970-01-01
          • 2013-06-22
          • 2016-09-22
          • 1970-01-01
          • 2012-04-30
          • 2017-02-14
          • 1970-01-01
          相关资源
          最近更新 更多