【问题标题】:why is std::chrono::duration based on seconds为什么 std::chrono::duration 基于秒
【发布时间】:2015-01-09 11:22:22
【问题描述】:

我正在学习 <chrono> 库,考虑到 std::chrono::duration 类,是否有任何特定的理由以秒为基础?例如,存储秒数的变量是

chrono::duration<int> two_seconds(2);

所有其他时间跨度都需要将它们与秒相关联,例如

chrono::duration<int, ratio<60>> two_minutes(2);
chrono::duration<int, ratio<1, 1000>> two_milliseconds(2);
chrono::duration<int, ratio<60 * 60 * 24>> two_days(2); 

是否有任何理由将持续时间基于秒而不是基于分钟、小时等?

【问题讨论】:

  • 秒是持续时间值的物理基准。可能是这个原因?
  • 如果是其他单位,你会问相应的问题吗?
  • 它必须基于something,因为它被存储为一个整数值和一个(整数的)比率。您还有什么建议作为基本单位?秒是最自然的,因为它是时间的SI unit
  • 如果要作为模板参数传递,这些类型将如何定义?我猜是通过使用某个基本单位的比率。这正是chrono::duration 自己所做的。如果您使用 std::chrono::milliseconds 类型(类型定义为您已经在第二行代码中发布的内容),您也可以使用毫秒作为“基础”
  • “有什么原因……不是分钟、小时等?” 感谢leap seconds,分钟和小时没有一致的持续时间。跨度>

标签: c++ chrono


【解决方案1】:

选择秒是因为它是 SI 系统和整个科学中的基本时间单位。
即使是美国人也使用秒,而不是微两周。

为什么这个基本时间跨度不是持续时间类的另一个模板参数

是的,因为您可以提供typedefs 的比率,其中一些包含在标准中。

#include <chrono>

std::chrono::duration<int, minutes> two_minutes(2);            // Standard
std::chrono::duration<int, milliseconds> two_milliseconds(2);  // Standard

如果您需要更多,添加它们很简单:

typedef std::ratio<60 * 60 * 24> days;
typedef std::ratio<756, 625> microfortnights;

std::chrono::duration<int, days> two_days(2); 
std::chrono::duration<int, microfortnights> two_weeks(1000000); 

【讨论】:

  • “即使是美国人也使用秒,而不是像微双周这样的东西。”为此 +1 :)
  • 该标准已经包含了std::chrono::milliseconds 之类的内容。请参阅this page 上标有“Helper Types”的部分。
  • @Steve 哎呀,我应该检查一下,而不是接受 OP 的话。
  • 现在开始为四月一日做准备永远不会太早...using microfortnights = duration&lt;long, std::ratio&lt;756,625&gt;&gt;; ;-)
  • @HowardHinnant 有达夫的规则说 pi 秒是一个纳米世纪
猜你喜欢
  • 2013-07-27
  • 2018-02-03
  • 1970-01-01
  • 2019-07-16
  • 2016-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多