C++ 记录代码运行时间

以前用的办法太老土啦

看到一个since C++11的方法,我觉得比较优雅

 1   #include <iostream>
 2   #include <chrono>
 3   //#include <ratio>
 4   #include <thread>
 5    
 6   void f()
 7   {
 8       std::this_thread::sleep_for(std::chrono::seconds(1));
 9   }
10    
11   int main()
12   {
13       auto t1 = std::chrono::high_resolution_clock::now();
14       f();
15       auto t2 = std::chrono::high_resolution_clock::now();
16   	
17       // floating-point duration: no duration_cast needed
18       std::chrono::duration<double, std::milli> fp_ms = t2 - t1;
19    
20       // integral duration: requires duration_cast
21       auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
22    
23       // converting integral duration to integral duration of shorter divisible time unit:
24       // no duration_cast needed
25       std::chrono::duration<long, std::micro> int_usec = int_ms;
26    
27       std::cout << "f() took " << fp_ms.count() << " ms, "
28                 << "or " << int_ms.count() << " whole milliseconds "
29                 << "(which is " << int_usec.count() << " whole microseconds)" << std::endl;
30   }
31
32