八_进程控制14 - 进程时间

这篇文章介绍了如何使用C语言中的times()函数来测量系统命令(如`date`、`sleep`和`manbash`)执行的CPU时间和用户CPU时间,展示了如何计算进程的上下文切换时间。

在这里插入图片描述

#include "unistd.h"
#include "sys/times.h"
#include "stdio.h"
#include "errno.h"
#include "sys/param.h"

void PrintTime(clock_t realTime,struct tms* startTime,struct tms* endTime)
{
	static long int clocktic=0;
	clocktic = sysconf(_SC_CLK_TCK);
	if(clocktic < 0)
		fprintf(stderr,"sysconf err");

	//注意 clock_t 是float类型,而clocktic 是long。运算需要类型转换
	fprintf(stdout,"real time : %f\n",realTime/(float)clocktic);
	fprintf(stdout,"Parent user cpu time : %f\n",(endTime->tms_utime - startTime->tms_utime)/(float)clocktic);
	fprintf(stdout,"Parent sys cpu time : %f\n",(endTime->tms_stime - startTime->tms_stime)/(float)clocktic);
	fprintf(stdout,"Child user cpu time : %f\n",(endTime->tms_cutime - startTime->tms_cutime)/(float)clocktic);
	fprintf(stdout,"Child sys cpu time : %f\n",(endTime->tms_cstime - startTime->tms_cstime)/(float)clocktic);

}

static void DoCmd(char *cmd)
{
	clock_t start,end;
	struct tms tms_start,tms_end; 
	int ret;
		
	start = times(&tms_start);
	if(start == -1)
		fprintf(stderr,"times err");

	if(system(cmd)<0)
		fprintf(stderr,"system err");

	end = times(&tms_end);
	if(end == -1)
		fprintf(stderr,"times err");
	
	PrintTime(end-start,&tms_start,&tms_end);

}

int main(int argc,char* argv[])
{	
	int i=0;
	for(i=1; i < argc; i++){
		DoCmd(argv[i]);
	}
	exit(0);
}



mhr@ubuntu:~/Desktop/xitongbiancheng/test$ ./a.out "date" "sleep 5" "man bash > /dev/null" 
2024年 04月 23日 星期二 02:14:07 PDT
real time : 0.010000
Parent user cpu time : 0.000000
Parent sys cpu time : 0.000000
Child user cpu time : 0.000000
Child sys cpu time : 0.000000


real time : 5.000000
Parent user cpu time : 0.000000
Parent sys cpu time : 0.000000
Child user cpu time : 0.000000
Child sys cpu time : 0.000000
real time : 0.260000
Parent user cpu time : 0.000000
Parent sys cpu time : 0.000000
Child user cpu time : 0.160000
Child sys cpu time : 0.030000
mhr@ubuntu:~/Desktop/xitongbiancheng/test$ 

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ma浩然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值