得到毫秒的时间

时间:2012-05-18 14:13:56

标签: c++

我需要从计时器

获得毫秒
    // 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的毫秒数?

提前致谢

8 个答案:

答案 0 :(得分:16)

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

答案 1 :(得分:6)

在使用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;
} 

答案 2 :(得分:5)

有getimeofday()函数。以ms为单位返回时间 点击此处:http://souptonuts.sourceforge.net/code/gettimeofday.c.html

答案 3 :(得分:4)

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

)

答案 4 :(得分:3)

你可以选择boost::posix_time::ptime课程。 它的reference there

答案 5 :(得分:2)

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

答案 6 :(得分:1)

在MS Visual Studio下,c / c ++包含sys / timeb.h并使用_ftime(_ftime_s)。 检索包含time_t结构和毫秒的struct _timeb(_ftime64),请参阅MSDN customerAddressUpdate

#include <sys/timeb.h>

struct _timeb timebuffer;
_ftime(&timebuffer);
timebuffer.millitm; //milli seconds
timebuffer.time; //the same like struct time_t

答案 7 :(得分:0)

尝试使用此代码:

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;