times函數用于獲取當前進程時間,其函數原型如下所示:
#include <sys/times.h>
clock_t times(struct tms *buf);? //使用該函數需要包含頭文件<sys/times.h>。
函數參數和返回值含義如下:
???????? buf:times()會將當前進程時間信息存在一個 struct tms 結構體數據中,所以我們需要提供 struct tms 變量,使用參數 buf 指向該變量 。
????????返回值:返回值類型為 clock_t(實質是 long 類型),調用成功情況下,將返回從過去任意的一個時間點(譬如系統啟動時間)所經過的時鐘滴答數(其實就是系統節拍數),將(節拍數 / 節拍率)便可得到秒數,返回值可能會超過 clock_t 所能表示的范圍(溢出);調用失敗返回-1,并設置 errno。
????????如果我們想查看程序運行到某一個位置時的進程時間,或者計算出程序中的某一段代碼執行過程所花費的進程時間,都可以使用 times()函數來實現。
struct tms {
?clock_t tms_utime; /* user time, 進程的用戶 CPU 時間, tms_utime 個系統節拍數 */clock_t tms_stime; /* system time, 進程的系統 CPU 時間, tms_stime 個系統節拍數 */
clock_t tms_cutime; /* user time of children, 已死掉子進程的 tms_utime + tms_cutime 時間總和 */
clock_t tms_cstime; /* system time of children, 已死掉子進程的 tms_stime + tms_cstime 時間總和 */
};?
代碼示例:
#include<stdio.h>
#include<stdlib.h>
#include<sys/times.h>
#include<unistd.h>int main(int argc ,char *agrv[])
{struct tms t_buf_start;struct tms t_buf_end;clock_t t_start; clock_t t_end;long tck;int i , j;/*獲取系統的節拍率*/tck = sysconf(_SC_CLK_TCK);/*開始時間*/t_start = times(&t_buf_start);if (-1 == t_start){perror("times error\n");exit(-1);}/*需要測試的代碼段*/for ( i = 0; i < 20000; i++){// }for ( j = 0; j < 20000; j++){/* code */}sleep(1); //休眠掛起/*結束時間*/t_end = times(& t_buf_end);if (-1 == t_end){/* code */perror("times error\n");exit(-1);}/*打印時間*/printf("時間總和: %f 秒\n", (t_end - t_start) / (double)tck);printf("用戶 CPU 時間: %f 秒\n", (t_buf_end.tms_utime - t_buf_start.tms_utime) / (double)tck);printf("系統 CPU 時間: %f 秒\n", (t_buf_end.tms_stime - t_buf_start.tms_stime) / (double)tck);exit(0);}
?運行結果:
clock 函數
庫函數 clock()提供了一個更為簡單的方式用于進程時間,它的返回值描述了進程使用的總的 CPU 時間(也就是進程時間,包括用戶 CPU 時間和系統 CPU 時間),其函數原型如下所示:
#include <time.h>
clock_t clock(void);使用該函數需要包含頭文件<time.h>。
?函數參數和返回值含義如下:
無參數。
返回值:返回值是到目前為止程序的進程時間,為 clock_t 類型,注意 clock()的返回值并不是系統節拍
數,如果想要獲得秒數,請除以 CLOCKS_PER_SEC(這是一個宏)。如果返回的進程時間不可用或其值無
法表示,則該返回值是-1。
clock()函數雖然可以很方便的獲取總的進程時間,但并不能獲取到單獨的用戶 CPU 時間和系統 CPU 時
間,在實際編程當中,根據自己的需要選擇。
代碼示例:
#include<stdio.h>
#include<stdlib.h>
#include<sys/times.h>
#include<unistd.h>#define CLOCKS_PER_SEC ((__clock_t) 1000000)
int clock();
int main(int argc ,char *agrv[])
{struct tms t_buf_start;struct tms t_buf_end;clock_t t_start; clock_t t_end;long tck;int i , j;/* 開始時間 */t_start = clock();if (-1 == t_start)exit(-1);/* *****需要進行測試的代碼段***** */for (i = 0; i < 20000; i++)for (j = 0; j < 20000; j++);/* *************end************** *//* 結束時間 */t_end = clock();if (-1 == t_end)exit(-1);/* 打印時間 */
printf("總的 CPU 時間: %f\n", (t_end - t_start) / (double)CLOCKS_PER_SEC);
exit(0);
}
運行結果: