在C++11中,是标准模板库中与时间有关的头文件。该头文件中所有函数与类模板均定义在std::chrono命名空间中。当我们想要记录模块代码或者函数的运算耗时的时候,可以利用chrono库实现。相关的代码如下:
#include <chrono> #include <iostream> class Timer { public: Timer(); virtual ~Timer(); int elapsedSecond(); int elapsedMillisecond(); int elapsedMicroSecond(); int elapsedNaoSecond(); private: std::chrono::high_resolution_clock::time_point start_; }; Timer::Timer() { start_ = std::chrono::high_resolution_clock::now(); } Timer::~Timer() {} int Timer::elapsedSecond() { return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start_).count(); } int Timer::elapsedMillisecond() { return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start_).count(); } int Timer::elapsedMicroSecond() { return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now()-start_).count(); } int Timer::elapsedNaoSecond() { return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now()-start_).count(); } int main() { Timer timer; std::cout << timer.elapsedNaoSecond()<< std::endl; std::cout << timer.elapsedMicroSecond() << std::endl; std::cout << timer.elapsedMillisecond() << std::endl; std::cout << timer.elapsedSecond() << std::endl; return 0; }