Get millisecond part of time

后端 未结 8 1915
再見小時候
再見小時候 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:07

    You can youse boost::posix_time::ptime class. Its reference there.

    0 讨论(0)
  • 2020-12-18 22:12

    there is the function getimeofday(). returns time in ms check here: http://souptonuts.sourceforge.net/code/gettimeofday.c.html

    0 讨论(0)
  • 2020-12-18 22:12

    On Windows using Win32 API SYSTEMTIME structure will give you milliseconds. Then, you should use Time Functions to get time. Like this:

    #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;
    } 
    
    0 讨论(0)
  • 2020-12-18 22:21

    Try with this code:

    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;
    
    0 讨论(0)
  • 2020-12-18 22:25

    I, personally, use this one: http://wyw.dcweb.cn/time.htm

    0 讨论(0)
  • 2020-12-18 22:26
    #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);
    

    Then you can print out the time_t with seconds precision and then print whatever the fraction represents. Could be milliseconds, microseconds, or something else. To specifically get milliseconds:

    auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(fraction);
    std::cout << milliseconds.count() << '\n';
    
    0 讨论(0)
提交回复
热议问题