如何在C++中获取毫秒级时间

7
在Java中,您可以这样做:
long now = (new Date()).getTime();

如何在C++中实现同样的功能?


请查看此线程(它是纳秒,但是我想它也可以转换为毫秒)https://dev59.com/MXVC5IYBdhLWcg3wfxQ8 - default
13
在Java中,您应该使用System.currentTimeMillis() - Steffen Heil
@SteffenHeil 来寻找美丽的C++,却也发现了美丽的Java,谢谢你。 - Jeromy Adofo
7个回答

14
因为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();

这个程序在gcc 4.4+上可以运行。使用--std=c++0x编译它。我不知道VS2010是否已经实现了std::chrono


duration_cast<duration<long, milliseconds>>表示将毫秒级别的长整型时间类型转换为其他时间类型。你打开了一个模板两次,但只关闭了一次...... - VDVLeon
你的 duration_cast 应该是:"auto millis = sc::duration_castsc::milliseconds(since_epoch);" - Howard Hinnant
这在我的系统上返回1434479941518,对应的日期是Sat, 11 Nov 47426 02:25:18 GMT。为什么会发生这种情况? - W.K.S
至少应该是“long long now”,否则您将获得负值。 - Andrey Suvorov

9

标准C++中没有这种方法(在标准C++中,只有秒级精度,而不是毫秒)。您可以使用非便携式的方式来实现,但由于您没有指定,因此我将假设您需要一种便携式的解决方案。我会建议您使用boost函数microsec_clock::local_time()


7

我希望有一个名为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);

以下实现应该适用于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

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


1
timeGetTime返回自Windows启动以来经过的时间,而不是距离Epoch的毫秒数。 - Matthew Flaschen
1
你可以在Windows上使用一些数学和GetSystemTimeAsFileTime(http://msdn.microsoft.com/en-us/library/ms724397%28v=VS.85%29.aspx)函数。个人而言,我喜欢`microsec_clock::local_time()` - 所有的艰苦工作已经完成了 :-) - Dean Harding
你能否同时更改 time_ms 原型上面的注释? - Matthew Flaschen

4
你可以尝试这段代码(从StockFish棋类引擎源码中获取(GPL)):

你可以尝试这段代码(从StockFish棋类引擎源码中获取(GPL)):

#include <iostream>
#include <stdio>

#if !defined(_WIN32) && !defined(_WIN64) // Linux - Unix
    #  include <sys/time.h>
    typedef timeval sys_time_t;
    inline void system_time(sys_time_t* t) {
        gettimeofday(t, NULL);
    }
    inline long long time_to_msec(const sys_time_t& t) {
        return t.tv_sec * 1000LL + t.tv_usec / 1000;
    }
    #else // Windows and MinGW
    #  include <sys/timeb.h>
    typedef _timeb sys_time_t;
    inline void system_time(sys_time_t* t) { _ftime(t); }
    inline long long time_to_msec(const sys_time_t& t) {
        return t.time * 1000LL + t.millitm;
    }
#endif


int main() {
    sys_time_t t;
    system_time(&t);
    long long currentTimeMs = time_to_msec(t);
    std::cout << "currentTimeMs:" << currentTimeMs << std::endl;
    getchar();  // wait for keyboard input
}

想知道 long long 是打错了还是有意为之? - ndtreviv
1
那是有意为之的;long long的长度是long的两倍,因此即使将系统时间乘以1000,它们也不太可能溢出。 - NullPointerException

3

0

-2

Java:

package com.company;

public class Main {

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());

    }
}

C++:

#include <stdio.h>
#include <windows.h>

__int64 currentTimeMillis() {
    FILETIME f;
    GetSystemTimeAsFileTime(&f);
    (long long)f.dwHighDateTime;
    __int64 nano = ((__int64)f.dwHighDateTime << 32LL) + (__int64)f.dwLowDateTime;
    return (nano - 116444736000000000LL) / 10000;
}

int main() {
    printf("%lli\n ", currentTimeMillis());

    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接