C庫函式clock_t clock(void) 返回自該計劃推出以來經過的時鐘滴答數。秒使用的CPU的數量,您將需要除以CLOCKS_PER_SEC。
CLOCKS_PER_SEC等於1000000在32位元系統中,這個函式將返回相同的值大約每72分鐘一次。
以下是clock() 函式的宣告。
clock_t clock(void)
NA
這個函式返回程式啟動以來經過的時鐘滴答數。失敗時,函式返回值-1。
下面的例子演示了如何使用clock() 函式。
#include <time.h> #include <stdio.h> int main() { clock_t start_t, end_t, total_t; int i; start_t = clock(); printf("Starting of the program, start_t = %ld ", start_t); printf("Going to scan a big loop, start_t = %ld ", start_t); for(i=0; i< 10000000; i++) { } end_t = clock(); printf("End of the big loop, end_t = %ld ", end_t); total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC; printf("Total time taken by CPU: %f ", total_t ); printf("Exiting of the program... "); return(0); }
讓我們編譯和執行上面的程式,這將產生以下結果:
Starting of the program, start_t = 0 Going to scan a big loop, start_t = 0 End of the big loop, end_t = 20000 Total time taken by CPU: 0.000000 Exiting of the program...