函数名: times
头文件: #include<sys/times>
函数声明: clock_t times(struct tms *buf);
参数介绍: man帮助查看: man 2 times
/* Structure describing CPU time used by a process and its children. */
struct tms
{
clock_t tms_utime ; /* User CPU time. 用户程序 CPU 时间*/
clock_t tms_stime ; /* System CPU time. 系统调用所耗费的 CPU 时间 */
clock_t tms_cutime ; /* User CPU time of dead children. 已死掉子进程的 CPU 时间*/
clock_t tms_cstime ; /* System CPU time of dead children. 已死掉子进程所耗费的系统调用 CPU 时间*/
};
概念:
1.实际时间(real time):从命令行执行到运行终止的消逝时间
2.用户CPU时间(user CPU time):命令执行完成花费的系统CPU时间,即命令在用户态中执行时的总和
3.系统CPU时间(system CPU time):命令执行完成花费的系统CPU时间,即命令在核心态中执行时间的总和。
4.cutime是用户CPU时间+子进程用户CPU时间。cstime同理。
函数使用说明:
times() 函数返回从过去一个任意的时间点所经过的时钟数,结合系统每秒的时钟可以通过 sysconf(_SC_CLK_TCK); 函数获得,可以计算出当前所处的时间点。
测试代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/times.h>
int main ()
{
struct tms time_buf_head , time_buf_end ;
long tck = 0 ;
clock_t time_head , time_end ;
tck = sysconf (_SC_CLK_TCK ); /*获取系统时钟(1秒里有多少个)*/
time_head = times ( & time_buf_head ); /*进程运行到此时的系统时钟数(总的)*/
printf ("head_time is : %f /n " , time_head / (double )tck ); /*此时进程所处的时间点(单位为秒)*/
//system ("./time_test.exe");
system ("sleep 2" ); /*睡眠2秒*/
time_end = times ( & time_buf_end ); /*进程到此时的系统时钟数*/
printf ("end_time is : %f /n " , time_end / (double )tck ); /*此时进程所处的时间点(单位为秒)*/
printf ("user time is : %f /n " , ((time_buf_end . tms_utime - time_buf_head . tms_utime ) /double )tck )); /*打印出用户进程到此所经历时间*/
printf ("systime time is : %f /n " , ((time_buf_end . tms_stime - time_buf_head . tms_stime) / double )tck ));
printf ("child user time is : %f /n " , ((time_buf_end . tms_cutime - time_buf_head .tms_cutime ) / (double )tck ));
printf ("child sys time is : %f /n " , ((time_buf_end . tms_cstime - time_buf_head .tms_cstime ) / (double )tck ));
return (0 );
}