如何使用C ++在Linux中获得总的CPU使用率 [英] How to get total cpu usage in Linux using C++

查看:126
本文介绍了如何使用C ++在Linux中获得总的CPU使用率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取总的CPU使用率(以%为单位).首先,我首先要说"top"不会做,因为cpu转储之间会有延迟,它需要2个转储和几秒钟的时间,这会使我的程序挂起(我不想给它自己的线程)

接下来我尝试的是"ps",它是即时的,但总的数字总是很高(20+),当我实际上让我的cpu做某事时,它保持在20左右...

还有其他方法可以获取总的CPU使用率吗?超过一秒还是更长的时间都没有关系.不过,更长的时间会更有用.

解决方案

cat/proc/stat

http://www.linuxhowtos.org/System/procstat.htm

我同意以上答案.该文件中的cpu行提供了系统在执行不同类型的处理时所花费的"jiffies"总数.

您需要做的是读取此文件的2个读数,并按需要的时间间隔分隔.这些数字是递增的值(取决于整数翻转),因此要获取%cpu,您需要计算在您的时间间隔内经过了多少次抖动,而花了多少次进行工作.

例如 假设您在14:00:00拥有

cpu 4698 591 262 8953 916 449 531

total_jiffies_1 =(所有值的总和)= 16400

work_jiffies_1 =(用户,尼斯,系统之和=前3个值)= 5551

在14:00:05您有

cpu 4739 591 289 9961 936 449 541

total_jiffies_2 = 17506

work_jiffies_2 = 5619

因此,此期间的%cpu使用量是:

work_over_period = work_jiffies_2-work_jiffies_1 = 68

total_over_period = total_jiffies_2-total_jiffies_1 = 1106

%cpu =工作时间段/总工作时间段* 100 = 6.1%

希望能有所帮助.

I am trying to get total cpu usage in %. First I should start by saying that "top" will simply not do, as there is a delay between cpu dumps, it requires 2 dumps and several seconds, which hangs my program (I do not want to give it its own thread)

next thing what I tried is "ps" which is instant but always gives very high number in total (20+) and when I actually got my cpu to do something it stayed at about 20...

Is there any other way that I could get total cpu usage? It does not matter if it is over one second or longer periods of time... Longer periods would be more useful, though.

解决方案

cat /proc/stat

http://www.linuxhowtos.org/System/procstat.htm

I agree with this answer above. The cpu line in this file gives the total number of "jiffies" your system has spent doing different types of processing.

What you need to do is take 2 readings of this file, seperated by whatever interval of time you require. The numbers are increasing values (subject to integer rollover) so to get the %cpu you need to calculate how many jiffies have elapsed over your interval, versus how many jiffies were spend doing work.

e.g. Suppose at 14:00:00 you have

cpu 4698 591 262 8953 916 449 531

total_jiffies_1 = (sum of all values) = 16400

work_jiffies_1 = (sum of user,nice,system = the first 3 values) = 5551

and at 14:00:05 you have

cpu 4739 591 289 9961 936 449 541

total_jiffies_2 = 17506

work_jiffies_2 = 5619

So the %cpu usage over this period is:

work_over_period = work_jiffies_2 - work_jiffies_1 = 68

total_over_period = total_jiffies_2 - total_jiffies_1 = 1106

%cpu = work_over_period / total_over_period * 100 = 6.1%

Hope that helps a bit.

这篇关于如何使用C ++在Linux中获得总的CPU使用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆