C++ 如何在C ++中以毫秒为单位获取时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2831841/
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-28 11:12:46  来源:igfitidea点击:

How to get the time in milliseconds in C++

c++time

提问by atomsfat

In Java you can do this:

在 Java 中,您可以这样做:

long now = (new Date()).getTime();

How can I do the same but in C++?

我怎么能做同样的事情,但在 C++ 中?

回答by deft_code

Because C++0x is awesome

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

This workswith gcc 4.4+. Compile it with --std=c++0x. I don't know if VS2010 implements std::chronoyet.

这适用于 gcc 4.4+。用--std=c++0x. 不知道VS2010有没有实现std::chrono

回答by Dean Harding

There is no such method in standard C++ (in standard C++, there is only second-accuracy, not millisecond). You can do it in non-portable ways, but since you didn't specify I will assume that you want a portable solution. Your best bet, I would say, is the boost function microsec_clock::local_time().

标准C++中没有这样的方法(在标准C++中,只有秒精度,没有毫秒)。您可以以非便携方式进行,但由于您没有指定,我将假设您需要一个便携解决方案。我想说,你最好的选择是 boost 函数microsec_clock::local_time()

回答by Joey Adams

I like to have a function called time_msdefined as such:

我喜欢这样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);

The implementation below should work in Windows as well as Unix-like systems.

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

Note that the time returned by the Windows branch is milliseconds since the system started, while the time returned by the Unix branch is milliseconds since 1970. Thus, if you use this code, only rely on differences between times, not the absolute time itself.

注意windows分支返回的时间是系统启动后的毫秒数,而Unix分支返回的时间是1970年以后的毫秒数。因此,如果你使用这段代码,只依赖时间之间的差异,而不是绝对时间本身。

回答by David R Tribble

Standard C++ does not have a time function with subsecond precision.

标准 C++ 没有亚秒级精度的时间函数。

However, almost every operating system does. So you have to write code that is OS-dependent.

但是,几乎每个操作系统都可以。所以你必须编写依赖于操作系统的代码。

Win32:
  GetSystemTime()
  GetSystemTimeAsFileTime()

Win32:
  GetSystemTime()
  GetSystemTimeAsFileTime()

Unix/POSIX:
  gettimeofday()
  clock_gettime()

Unix/POSIX:
  gettimeofday()
  clock_gettime()

回答by TrungTN

You can try this code (get from StockFish chess engine source code (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
}

回答by JH.

Boost has a useful library for doing this:

Boost 有一个有用的库来执行此操作:

http://www.boost.org/doc/libs/1_43_0/doc/html/date_time.html

http://www.boost.org/doc/libs/1_43_0/doc/html/date_time.html

ptime microsec_clock::local_time() or ptime second_clock::local_time()

ptime microsec_clock::local_time() 或 ptime second_clock::local_time()

回答by ilw

Java:

Java:

package com.company;

public class Main {

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

    }
}

c++:

c++:

#include <iostream>
#include <windows.h>

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

int main() {

    printf("%lli\n ", currentTimeMillis());

    return 0;
}