1. 程式人生 > >常用的三種獲取程式執行時間的方法

常用的三種獲取程式執行時間的方法

#include <chrono>    //C++11
chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
domeSomething();
chrono::steady_clock::time_point t2 = chrono::steady_clock::now();
chrono::duration<double> time_used = chrono::duration_cast<chrono
::duration<double>>(t2 - t1); cout<<"solve time cost = "<<time_used.count()<<" secondes."<<endl;
  • ctime
#include <ctime>
using namespace std;
clock_t start = clock();
// do something...
clock_t end   = clock();
cout << "花費了" << (double)(end - start) / CLOCKS_PER_SEC << "秒"
<< endl; //此方法測出來的時間經常不準,不建議使用
  • gettimeofday
#include <time.h>
using namespace std;
timeval start, end;
gettimeofday(&start, NULL);
// do somethind
gettimeofday(&end, NULL);
cout << "花費了" << end.tv_sec - start.tv_sec << " s." << endl;
cout << "花費了"
<< end.tv_usec - start.tv_usec << " us." << endl;