C 庫函數(shù) clock_t clock(void) 返回程序執(zhí)行起(一般為程序的開頭),處理器時(shí)鐘所使用的時(shí)間。為了獲取 CPU 所使用的秒數(shù),您需要除以 CLOCKS_PER_SEC。
在 32 位系統(tǒng)中,CLOCKS_PER_SEC 等于 1000000,該函數(shù)大約每 72 分鐘會(huì)返回相同的值。
下面是 clock() 函數(shù)的聲明。
clock_t clock(void)
該函數(shù)返回自程序啟動(dòng)起,處理器時(shí)鐘所使用的時(shí)間。如果失敗,則返回 -1 值。
下面的示例演示了 clock() 函數(shù)的用法。
#include <time.h>
#include <stdio.h>
int main()
{
clock_t start_t, end_t;
double total_t;
int i;
start_t = clock();
printf("程序啟動(dòng),start_t = %ld\n", start_t);
printf("開始一個(gè)大循環(huán),start_t = %ld\n", start_t);
for(i=0; i< 10000000; i++)
{
}
end_t = clock();
printf("大循環(huán)結(jié)束,end_t = %ld\n", end_t);
total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
printf("CPU 占用的總時(shí)間:%f\n", total_t );
printf("程序退出...\n");
return(0);
}讓我們編譯并運(yùn)行上面的程序,這將產(chǎn)生以下結(jié)果:
程序啟動(dòng),start_t = 2614 開始一個(gè)大循環(huán),start_t = 2614 大循環(huán)結(jié)束,end_t = 28021 CPU 占用的總時(shí)間:0.025407 程序退出...