linux 統計 程式 已耗用時間

來源:互聯網
上載者:User

測試 代碼已耗用時間

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 timezone11 * {12 * int tz_minuteswest; // minutes west of Greenwich13 * int tz_dsttime; // type of DST correction14 * }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 time12     //-------------------------13     14     // test code15     while(i)16     {17         i--;18     }19 20     //-------------------------21     gettimeofday(&end, NULL);  // get the end time22     //-------------------------23     24     long long total_time = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // get the run time by microsecond25     printf("total time is %lld us\n", total_time);26     total_time /= 1000; // get the run time by millisecond27     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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.