在优化某段程序以前,咱们每每须要肯定其运行时间,经过对比优化先后的时间,来衡量优化的力度。函数
那么问题来了,除了借助操做系统 time
命令这种方式,有没有直接在代码中嵌入时间测量的方法呢?优化
C++ 中比较传统的方式是使用 C 库中的<ctime>
.spa
cpp#include <ctime> using namespace std; int main() { clock_t begin = clock(); // your codes clock_t end = clock(); double elapsed_secs = static_cast<double>(end - begin) / CLOCKS_PER_SEC; cout << elapsed_secs << " s" << endl; }
这种方式其实是能够精确到毫秒的,若是再想更加精确,就有点难了。操作系统
今天介绍一种借助 std::chrono::duration
与 lambda 函数的方法,相比之下更加 C++ 一些。code
cpp#include <chrono> template<typename TimeT = std::chrono::milliseconds> struct measure { template<typename F, typename ...Args> static typename TimeT::rep execution(F func, Args&&... args) { auto start = std::chrono::system_clock::now(); // Now call the function with all the parameters you need. func(std::forward<Args>(args)...); auto duration = std::chrono::duration_cast< TimeT> (std::chrono::system_clock::now() - start); return duration.count(); } }; struct functor { int state; functor(int state) : state(state) {} void operator()() const { std::cout << "In functor run for "; } }; void func() { std::cout << "In function, run for " << std::endl; } int main() { // codes directly std::cout << measure<>::execution([&]() { // your code }) << " ms" << std::endl; // functor std::cout << measure<>::execution(functor(3)) << std::endl; // function std::cout << measure<>::execution(func); }
改变精度,仅需修改 template<typename TimeT = std::chrono::milliseconds>
中的参数便可:get