為了測試程式的效能,我們常常需要使用計時函式。在c++中提供了多種實現計時的方式。下面主要說明gettimeofday和clock函式的使用。
gettimeofday獲取的是當前精確時間(2023年1月1日到現在的時間),或者為執行計時,也可以稱之為牆上時間。在程式執行之前獲取一次時間,執行結束之後獲取一次時間,兩次時間之差就是程式真正的執行時間。
而clock為cpu的時間,其中包括使用者**,庫函式,系統呼叫等消耗的時間,但是不包括cpu的空閒時間(程序切換,等待訊息消耗的時間)。在多工的系統中,在涉及到程序切換的時候,clock能獲得某個單一程序在cpu中的執行時間。而gettimeofday只能獲得從程式開始執行到程式執行結束的時間,其中可能包括程序被切換出去的時間。
兩個函式的具體用法如下:
#include#include#include #includeusing namespace std;
struct timeval start1,end1;
clock_t begin, finish;
int main()
cout << sum << endl;
gettimeofday(&end1,null);
finish = clock(); //結束計時
double timeuse = end1.tv_sec - start1.tv_sec + (end1.tv_usec - start1.tv_usec)/1000000.0;
cout << "the time of gettimeofday is " << timeuse << endl; //列印結果
timeuse = (double)(finish - begin) / clocks_per_sec;
cout << "the time of clock is " << timeuse << endl; //列印結果
return 0;
}
執行結果
明顯看出gettimeofday的時間長於clock的時間,其中可能就包括了程式被切換出去的而等待的時間。xiang@xiang:~/workspace/system_lib$ ./time
-1243309312
the time of gettimeofday is 3.09654
the time of clock is 2.92
在並行程式記錄時間的時候,為了獲取從程式開始到程式執行結束的時間一般使用gettimeofday.
C語言的計時函式
include time.h 最常用的無疑是time函式,用法如下 int start,end start time null 獲得當前系統執行時間 處理事件 end time null 獲得處理完事件後系統執行時間 put end start 但是time函式用來計時並不是特別的精確,只是精確到s...
C 程式計時函式
有時候需要對程式某個部分進行計時 上 double timecost total 0 large integer m nfreq large integer m nbegintime large integer nendtime inline void starttiming inline void...
C 的幾種計時函式示例
評估一段 的執行時間時候,一般在 開始和結束位置放乙個時間戳,然後兩個時間戳相減即可。方法1和方法2的時間是一致的,方法3在linux上有時候不准。時間單位縮寫對應 s 秒 ms 毫秒 s 微秒 ns 納秒 1s 1000ms 1000 000 s 1000 000 000ns。精度情況 示例 的單...