linux获取当前进程的CPU使用率

网上win下有好多例子,但是linux下的几乎没有。

查看了下win下获取的原理,就是一段时间里,系统态运行时间加上用户态运行时间,除以这段时间,就所CPU使用率。

仿照写了以下代码

先所获取当前时间的函数,用于计算时间流逝,精确到纳秒。

int64_t	get_ticket()
{
	struct timespec ts;
	int64_t	ustime = 0;
	clock_gettime(CLOCK_MONOTONIC, &ts);
	return ts.tv_sec*1.0e9+ts.tv_nsec;
}

然后获取程序总的运行时间,可以使用getrusage()函数,返回的struct rusage结构体里面有两个time_val结构记录程序在用户和系统态运行的时间。

bool	get_time_info(int64_t& systime, int64_t& nowtime)
{	
	struct rusage rus;
	if (getrusage(RUSAGE_SELF, &rus) == 0)
	{
		int64_t use_time = rus.ru_utime.tv_sec*1.0e9 + rus.ru_utime.tv_usec*1.0e3; // 用户态所用时间
		int64_t sys_time = rus.ru_stime.tv_sec*1.0e9 + rus.ru_stime.tv_usec*1.0e3; // 系统态所用时间
		systime = use_time + sys_time;  // 记录当前总时间
		nowtime = get_ticket();		// 记录当前时间
		return true;
	}
	return false;
}

最后一个函数则是根据2次时间差计算CPU使用率

double	get_cpu_usage_linux()
{
	static int cpu_count = sysconf(_SC_NPROCESSORS_CONF); // cpu core number
	
	double cpu = 0;
	int64_t systime=0, nowtime=0;	
	if (get_time_info(systime, nowtime)) // 记录上一次运行的状态
	{
		sleep(1);		// 间隔一秒
		int64_t systime2=0, nowtime2=0;
		if (get_time_info(systime2, nowtime2)) // 获得现在的状态
		{
			cpu = ((double)(systime2-systime)/(double)(nowtime2-nowtime))*(100/cpu_count); // 计算出cpu使用率
			return cpu;
		}
	}
}

测试测试下效果:

void* thread(void*) // 死循环占满一个cpu
{
	int64_t i = 0;
	while(1)
		i = get_ticket()*get_ticket();
	return 0;
}
int main()
{
	pthread_t id;
	pthread_create(&id, 0, thread, 0);
	while (1)
		printf("cpu usage: %u%%\r\n", (int)get_cpu_usage_linux());
	return 0;
}

输出结果:

root@ubuntu:/home/zcw# ./a.out
cpu usage: 49%
cpu usage: 49%
cpu usage: 49%


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值