以毫秒为单位获取自纪元以来的时间,最好使用 C++11 chrono

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

Get time since epoch in milliseconds, preferably using C++11 chrono

c++c++11chrono

提问by Haatschii

All I want is to get the time since epoch in milliseconds and store it in an unsigned long.

我想要的只是以毫秒为单位获取自纪元以来的时间并将其存储在 unsigned long 中。

I found this related question. But honestly, this can't be the easiest way to perform such a simple task, is it? I am hoping for something much simpler, but can't find anything in the std::chrono reference. Any advice is most welcome. I don't necessarily have to use std::chrono, but I want it to be platform independent.

我发现了这个相关的问题。但老实说,这不是执行如此简单任务的最简单方法,是吗?我希望有更简单的东西,但在std::chrono 参考中找不到任何东西。任何建议都是最受欢迎的。我不一定必须使用std::chrono,但我希望它独立于平台。

回答by Mike Seymour

unsigned long milliseconds_since_epoch =
    std::chrono::system_clock::now().time_since_epoch() / 
    std::chrono::milliseconds(1);

although, especially since you want platform independence, it might be better to replace unsigned longwith a type that's more likely to be large enough:

虽然,特别是因为您想要平台独立性,最好unsigned long用更可能足够大的类型替换:

  • (unsigned) long long
  • std::(u)int64_t
  • std::chrono::milliseconds::rep
  • auto
  • (unsigned) long long
  • std::(u)int64_t
  • std::chrono::milliseconds::rep
  • auto

To me, this clearly states both that you're risking loss of precision (by analogy with integer division) andthat you're leaving the safety of the type system (by dividing by a typed time to give a unitless number). However, as demonstrated in the comments, some people would say that any attempt to move away from type-safety should be accompanied by a deliberate attempt to make the code look dangerous. If you need to deal with people who hold that belief, it might be simpler to use duration_castrather than enter into an argument about irrelevant stylistic choices:

对我来说,这清楚地表明您冒着失去精度的风险(与整数除法类比)并且您正在离开类型系统的安全性(通过除以类型化时间给出无单位数)。然而,正如评论中所展示的,有些人会说,任何试图摆脱类型安全的尝试都应该伴随着故意使代码看起来很危险的尝试。如果您需要与持有这种信念的人打交道,使用它可能更简单,duration_cast而不是就不相关的风格选择进行争论:

unsigned long milliseconds_since_epoch = 
    std::chrono::duration_cast<std::chrono::milliseconds>
        (std::chrono::system_clock::now().time_since_epoch()).count();