2010年6月30日 星期三

[C++]計算程式執行時間

兩個解決方案

// C 的寫法, in second,只能精準到秒
#include "stdio.h"
#include "time.h"
#include "stdlib.h"
int main(int argc, char *argv[]){
  time_t start;
  time_t end;
  start = time (&start); 
  // do something here
  end = time (&end);
  cout <<"time:" << end - start << endl;
}



// C++的寫法,in millisecond,可計算到零點多秒
#include "stdio.h"
#include "time.h"
#include "stdlib.h"
int main(int argc, char *argv[]){
  clock_t start_time, end_time;
  float total_time = 0;
  start_time = clock(); /* mircosecond */
  //do something here
  end_time = clock();

   /* CLOCKS_PER_SEC is defined at time.h */
    total_time = (float)(end_time - start_time)/CLOCKS_PER_SEC;

    printf("Time : %f sec \n", total_time);
}

沒有留言: