測試 代碼運行時間
linux 中的 <sys/time.h> 中 有個函數可以獲取當前時間,精確到 微秒 ----> gettimeofday()
1 #include <sys/time.h>
// int gettimeofday(struct timeval *tv, struct timezone *tz); 2 /********************************************* 3 * struct timeval 4 * { 5 * time_t tv_sec; // seconds 6 * suseconds_t tv_usec; // microseconds:微秒 10^(-6)s, 這里的 tv_sec 用的是 微秒 7 * // millisecond :毫秒 10^(-3)s 8 * } 9 ********************************************** 10 * struct timezone 11 * { 12 * int tz_minuteswest; // minutes west of Greenwich 13 * int tz_dsttime; // type of DST correction 14 * } 15 **********************************************/
使用時,定義兩個 struct timeval 變量(通常 gettimeofday() 的第二個參數 設為 NULL),分別保存 代碼測試 前后的時刻,最后相減,即可獲取 代碼運行時間 (可轉換為自己需要的時間)。
1 #include <stdio.h> 2 #include <sys/time.h> // for gettimeofday() 3 #include <string.h> // for memset() 4 5 int main() 6 { 7 int i = 10000000; 8 struct timeval start, end; // define 2 struct timeval variables 9 10 //------------------------- 11 gettimeofday(&start, NULL); // get the beginning time 12 //------------------------- 13 14 // test code 15 while(i) 16 { 17 i--; 18 } 19 20 //------------------------- 21 gettimeofday(&end, NULL); // get the end time 22 //------------------------- 23 24 long long total_time = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // get the run time by microsecond 25 printf("total time is %lld us\n", total_time); 26 total_time /= 1000; // get the run time by millisecond 27 printf("total time is %lld ms\n", total_time); 28 }
測試結果:(CentOS 6.5, gcc 4.4.7)
total time is 49658 us
total time is 49 ms