C++中的时间计算

来源:互联网 发布:道亨软件多少钱 编辑:程序博客网 时间:2024/06/15 09:39

在跑程序的过程中经常需要计算某个业务运行了多久,查看是哪个部分所占的时间比较长,之前一直用gettimeofday()函数,但那个比较麻烦,还需要用结构体,然后从中取各个时间,今天突然发现boost提供了一个直接可用且更方便的库(好吧今天才知道不要嘲笑我)
为了方便以后查找,先贴出boost的posix_time库的官方使用示例:
http://www.boost.org/doc/libs/master/doc/html/date_time/examples.html#date_time.examples.time_math
最常用的当属计算开始时间、结束时间,并以此计算耗费时间
小例子:

#include "boost/date_time/posix_time/posix_time.hpp"#include <iostream>int main(){    boost::posix_time::ptime tick = boost::posix_time::microsec_clock::local_time();    int i = 100000;    while(i--) {        std::cout << i << std::endl;    }    boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();    boost::posix_time::time_duration diff = now - tick;    std::cout << "now is:" <<now << std::endl;    std::cout << "diff is:" << diff << std::endl;    std::cout << "now date is:" << now.date()<< std::endl;           boost::posix_time::ptime tomorrow_start(now.date());    //这个厉害了,很多场景需要每天凌晨12点计算或者更新的业务,可以直接用这个    std::cout << "tomorrow_start is:" <<tomorrow_start<< std::endl;    return 0;}

还有很多用法, 目前没用上也就没有整理,如果用得上的时候可以直接看官网例子,还是很方便的