C++ chrono - 获取持续时间为浮点数或长整型

5
我有一个持续时间。
typedef std::chrono::high_resolution_clock Clock;
Clock::time_point       beginTime;
Clock::time_point       endTime;
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - beginTime);

我得到了std::chrono::millisecondsduration。但是我需要将duration作为floatlong long。怎么做呢?


3
在在SO上发帖之前,阅读文档去了哪里? - Kerrek SB
5
我已阅读,但抱歉,“返回 ticks 数量”对我来说没有任何意义。 - Narek
1
@Narek 这个计算结果是一个时间数量吗?它是否无单位?还是一个距离的数量? - bames53
1
@Narek:听起来你想要将速度和时间相乘,得到一个距离,然后将其加到位置上,以获得表示运动的新位置?注意这个问题中没有包含“float”或者“scalar”这个词?location += velocity * duration; - Mooing Duck
显示剩余6条评论
2个回答

8

以下是来自文档的内容:

template<
    class Rep, 
    class Period = std::ratio<1> 
> class duration;

Class template std::chrono::duration represents a time interval. It consists of a count of ticks of type Rep and a tick period, where the tick period is a compile-time rational constant representing the number of seconds from one tick to the next.

并且:

count 返回ticks的数量

因此,持续时间存储指定时间段的tick数量,并且count将使用底层表示类型返回该数字。因此,如果持续时间的表示形式为long long,而周期为std::milli,则.count()将返回一个等于由持续时间表示的毫秒数的long long


通常应避免使用弱类型,如floatlong long表示持续时间。相反,您应坚持使用“富”类型,如std :: chrono :: milliseconds或适当的std :: chrono :: duration专业化。这些类型有助于正确的使用和可读性,并通过类型检查帮助防止错误。

  • 未明确说明/过于一般:
    – void increase_speed(double);
    – Object obj; … obj.draw();
    – Rectangle(int,int,int,int);

  • 更好: – void increase_speed(Speed);
    – Shape& s; … s.draw();
    – Rectangle(Point top_left, Point bottom_right);
    – Rectangle(Point top_left, Box_hw b);

— slide 18 from Bjarne's talk


std::chrono是一个“物理量库的一致子集,仅处理时间单位,且只处理阶数等于0和1的那些时间单位。”在此处

如果需要使用时间量,请利用此库或提供更完整单元系统的库,例如boost :: units

有时必须将数量降级为弱类型。例如,当必须使用需要此类类型的API时。否则应避免使用。


0

作为 float 的答案。

std::chrono 的 duration 类型定义是整数。然而,duration 类可以接受 float

看看我的 duration 类型定义:

https://github.com/faithandbrave/Shand/blob/master/shand/duration.hpp

...
template <class Rep>
using seconds_t = std::chrono::duration<Rep>;
using seconds_f = seconds_t<float>;
using seconds_d = seconds_t<double>;
using seconds_ld = seconds_t<long double>;

template <class Rep>
using minutes_t =  std::chrono::duration<Rep, std::ratio<60>>;
using minutes_f = minutes_t<float>;
using minutes_d = minutes_t<double>;
using minutes_ld = minutes_t<long double>;
...

这些时间段的使用方法在这里:
#include <iostream>
#include <shand/duration.hpp>

int main()
{
    std::chrono::seconds int_s(3);
    shand::minutes_f float_m = int_s; // without `duration_cast`

    std::cout << float_m.count() << std::endl; // 0.05
}

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