Get millisecond part of time

后端 未结 8 1916
再見小時候
再見小時候 2020-12-18 22:07

I need to get milliseconds from the timer

    // get timer part
    time_t timer = time(NULL);
    struct tm now = *localtime( &timer );
    char timesta         


        
相关标签:
8条回答
  • 2020-12-18 22:29

    under MS Visual Studio c/c++ include sys/timeb.h and use _ftime (_ftime_s). Retrieves a struct _timeb (_ftime64) containing the time_t struct and also milli seconds, see 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
    
    0 讨论(0)
  • 2020-12-18 22:32

    Here is another c++11 answer:

    #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;
    }
    
    0 讨论(0)
提交回复
热议问题