存档

文章标签 ‘duration’

C++11/14 新特性 (使用 chrono 进行时间处理)

2017/01/03 7,512

在c++11以前,我们获取当前时间的时间戳,需要借助于第三方库,如 boost ,或者针对不同的操作做不同的处理:

#ifndef _MSC_VER
#include <sys/time.h>
#endif

long long GetTimeSpan()
{
    long long llTimeMs = 0L;
#ifdef _MSC_VER
    timeb tb;
    ftime(&tb);

    lTimeMs = tb.time * 1000 + tb.millitm;

#else
    timeval tmv;
    gettimeofday(&tmv,NULL);


    llTimeMs = (long long)(tmv.tv_sec) * 1000L + tmv.tv_usec / 1000;

#endif
    return llTimeMs;
}

而在c++11中,这个问题得到解决。 c++11 标准库中提供 chrono库,用来处理时间相关的数据。

1 duration 记录时长

duration 表示一段时间间隔。其原型:

template <class _Rep, class _Period>
class duration;

_Rep 为一个数值类型,如 int, long, 用来表示时钟数的类型。 _Period 为一个默认的模板参数 std::ratio,表示时钟周期。 ratio的原型:

template <intmax_t _Num, intmax_t _Den = 1>
class ratio

它表示一个时钟周期的秒数。_Num 代表分子,_Den代表分母,它们的比值就是一个时钟周期,可以通过调整分子与分母来表示任意一个时钟周期。如 ratio<1> 表示一个时钟周期为1秒,ratio<3600>表示一个时钟周期为1小时,ratio<1,1000>表示一个时钟周期为1毫秒,ratio<1,2>表示一个时钟周期为0.2秒,ratio<9/7>表示一个时钟周期为9/7秒。 标准库将一些常用的时钟周期做了定义:

typedef ratio<1LL, 1000000000000000000LL> atto;
typedef ratio<1LL,    1000000000000000LL> femto;
typedef ratio<1LL,       1000000000000LL> pico;
typedef ratio<1LL,          1000000000LL> nano;
typedef ratio<1LL,             1000000LL> micro;
typedef ratio<1LL,                1000LL> milli;
typedef ratio<1LL,                 100LL> centi;
typedef ratio<1LL,                  10LL> deci;
typedef ratio<                 10LL, 1LL> deca;
typedef ratio<                100LL, 1LL> hecto;
typedef ratio<               1000LL, 1LL> kilo;
typedef ratio<            1000000LL, 1LL> mega;
typedef ratio<         1000000000LL, 1LL> giga;
typedef ratio<      1000000000000LL, 1LL> tera;
typedef ratio<   1000000000000000LL, 1LL> peta;
typedef ratio<1000000000000000000LL, 1LL> exa;

typedef duration<long long,         nano> nanoseconds;
typedef duration<long long,        micro> microseconds;
typedef duration<long long,        milli> milliseconds;
typedef duration<long long              > seconds;
typedef duration<     long, ratio<  60> > minutes;
typedef duration<     long, ratio<3600> > hours;

在不同的时钟周期中,我们可以使用 chrono_cast 来进行转换。两个 duration还可以进行加减运算:

#include <chrono>
#include <iostream>
using namespace std;

int main(int argc, const char * argv[]) {

    chrono::hours hrs(2);   //两小时
    cout<<hrs.count()<<" hours = ";  //count() 函数获取时钟周期下的时钟数
    chrono::minutes mns = chrono::duration_cast<chrono::minutes>(hrs); //120分钟
    cout<<mns.count()<<" minutes"<<endl;

    chrono::minutes tm = hrs - chrono::minutes(30);  //时长的加减运算
    cout<<hrs.count()<<" hours - 30 minutes = " <<tm.count()<<" minutes = ";

    typedef chrono::duration<double,ratio<3600,1>> hs;  //时长的类型转换。注意 duration 的 _Rep 参数类型。
    hs c = chrono::duration_cast<hs>(tm);
    cout<<c.count()<<" hours"<<endl;


    return 0;
}

//#  输出 #:
// 2 hours = 120 minutes
// 2 hours - 30 minutes = 90 minutes = 1.5 hours

继续阅读