在優化某段程序以前,咱們每每須要肯定其運行時間,經過對比優化先後的時間,來衡量優化的力度。函數
那麼問題來了,除了藉助操做系統 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