如何像java一样在c ++中获得毫秒的时间

ato*_*fat 7 c++ time

在Java中,您可以这样做:

long now = (new Date()).getTime();
Run Code Online (Sandbox Code Playgroud)

我怎么能用c ++做同样的事情?

def*_*ode 12

因为C++ 0x很棒

namespace sc = std::chrono;

auto time = sc::system_clock::now(); // get the current time

auto since_epoch = time.time_since_epoch(); // get the duration since epoch

// I don't know what system_clock returns
// I think it's uint64_t nanoseconds since epoch
// Either way this duration_cast will do the right thing
auto millis = sc::duration_cast<sc::milliseconds>(since_epoch);

long now = millis.count(); // just like java (new Date()).getTime();
Run Code Online (Sandbox Code Playgroud)

这适用于gcc 4.4+.用它编译--std=c++0x.我不知道VS2010是否实现std::chrono了.


Dea*_*ing 9

标准C++中没有这样的方法(在标准C++中,只有第二精度,而不是毫秒).你可以用非便携的方式做到这一点,但既然你没有指定,我会假设你想要一个可移植的解决方案.我想说,你最好的选择是boost函数microsec_clock :: local_time().


Joe*_*ams 5

我喜欢这样time_ms定义一个函数:

// Used to measure intervals and absolute times
typedef int64_t msec_t;

// Get current time in milliseconds from the Epoch (Unix)
// or the time the system started (Windows).
msec_t time_ms(void);
Run Code Online (Sandbox Code Playgroud)

下面的实现应该适用于Windows以及类Unix系统.

#if defined(__WIN32__)

#include <windows.h>

msec_t time_ms(void)
{
    return timeGetTime();
}

#else

#include <sys/time.h>

msec_t time_ms(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (msec_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

#endif
Run Code Online (Sandbox Code Playgroud)

请注意,自从系统启动以来,Windows分支返回的时间是毫秒,而自1970年以来Unix分支返回的时间是毫秒.因此,如果使用此代码,则仅依赖于时间之间的差异,而不是绝对时间本身.