如何在Linux中获得总cpu使用率(c ++) [英] How to get total cpu usage in Linux (c++)
问题描述
我想在%中获得总cpu使用率。首先我应该开始说,top根本不会做,因为在cpu转储之间有一个延迟,它需要2转储和几秒钟,这挂了我的程序(我不想给它自己的线程) p>
下一件事,我尝试的是ps是即时的,但总是提供非常高的数字(20+),当我实际上有我的cpu做某事,它停留在约20 ...
有没有其他方法,我可以得到总cpu使用?
blockquote>
cat / proc / stat
http://www.linuxhowtos.org/System/procstat.htm
我同意上述答案。该文件中的cpu行给出了您的系统在处理不同类型处理时所使用的jiffies总数。
您需要做的是读取这个文件,由您需要的任何时间间隔分隔。数字是增加的值(以整数滚动),所以得到%cpu你需要计算在你的间隔过去了多少个jiffies花费在做工作的jiffies。
p
假设在14:00:00您有
cpu 4698 591 262 8953 916 449 531
total_jiffies_1 =(所有值的总和)= 16400
work_jiffies_1 =(用户总数,nice,system =前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
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
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.
这篇关于如何在Linux中获得总cpu使用率(c ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!