[C/C++11]_[初级]_[实用时间库chrono]

场景

  1. C++11开始提供了一个 实用时间库,相比C的time_t强多了,最明显的是可以精确到纳秒.
  2. vs2010还不支持这个库,所以比较可惜,对于新开发的项目,建议用2015可以使用最新特性.
  3. 一般用这个库来转换时间或计算函数执行时间或者CPU指令周期.

例子


#include <iostream> 
#include <algorithm>
#include <sstream>
#include <stdlib.h> 
#include <string.h> 
#include <string>
#include <assert.h>
#include <ctype.h> 
#include <vector> 
#include <Windows.h>
#include <chrono>
#include <iomanip>
#include <stdint.h>

using namespace std;  

class A
{
public:
    int i_;
};

int64_t Factorial(int gene)
{
    return (gene == 1)?1:gene*Factorial(gene-1);
}


void TestChrono()
{
    // 计算函数执行时间.
    auto start = std::chrono::steady_clock::now();
    std::vector<A*> v;
    for (int i = 1; i <= 1000000; ++i)
    {
        v.push_back(new A());
    }

    for (auto a : v)
    {
        delete a;
    }

    auto end = std::chrono::steady_clock::now();
    std::chrono::duration<double> diff = end-start;
    std::cout << "=>Time Elapse " << diff.count() << " s" << std::endl;

    // 获取过去24小时的时间
    std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
    std::time_t now_c = std::chrono::system_clock::to_time_t(now - std::chrono::hours(24));
    char buf[32];
    strftime(buf,32,"%Y-%m-%d %H:%M:%S",std::localtime(&now_c));
    std::cout << buf << std::endl;

    // time_t t;
    // t = time(NULL);
    // std::stringstream ss;
    // ss << put_time(localtime(&t),"%Y-%m-%d %H:%M:%S");
    // std::string str = ss.str();
    // std::cout << "str: " << str << std::endl;
}

int main(int argc, char const *argv[])  
{  
    TestChrono();
    return 0;  
}  

输出

=>Time Elapse 0.35702 s 2016-05-29 14:26:52

参考

chrono
time_point
put_time

你可能感兴趣的:(日期,C++11,执行时间,计算时间,chrono)