C++ 获取毫秒部分时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10654258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:18:21  来源:igfitidea点击:

Get millisecond part of time

c++

提问by olidev

I need to get milliseconds from the timer

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

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

I want to get like this in C#:

我想在 C# 中变成这样:

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

I tried using %f or %F but it does work with C++. how can I get %f for milliseconds from tm?

我尝试使用 %f 或 %F 但它确实适用于 C++。我怎样才能从 tm 获得 %f 毫秒?

采纳答案by amanda

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

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

回答by bames53

#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:

然后你可以打印出具有秒精度的 time_t,然后打印任何分数代表的内容。可能是毫秒、微秒或其他。要专门获得毫秒:

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

回答by SChepurin

On Windows using Win32 API SYSTEMTIME structurewill give you milliseconds. Then, you should use Time Functionsto get time. Like this:

在 Windows 上使用 Win32 API SYSTEMTIME 结构会给你毫秒。然后,您应该使用时间函数来获取时间。像这样:

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

回答by Chris Desjardins

Here is another c++11 answer:

这是另一个 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;
}

回答by inkooboo

You can youse boost::posix_time::ptimeclass. Its reference there.

你可以boost::posix_time::ptime上课。它的参考在那里

回答by John Kaul

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

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

回答by steven j

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

在 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

回答by jeremy

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;