电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術(shù)文章
文章詳情頁

Linux中計算特定CPU使用率案例詳解

瀏覽:168日期:2022-06-03 11:15:20

Linux中計算特定CPU使用率 需求解決方案拓展參考

需求

在Linux中可以通過top指令查看某一進程占用的CPU情況,也可以查看某一個CPU使用率情況(先top指令,然后按數(shù)字“1”鍵即可顯示每一個CPU的使用情況),如下圖:

而我們的需求是:如何得到一個CPU的占用率呢?

解決方案

1. 背景知識

在/proc/stat中可以查看每一個CPU的使用情況的,如下圖:

其中cpu(0/1/2/…)后面的那十個數(shù)字含義如下:

/proc/statkernel/system statistics.  Varies with architecture.  Common entries include:     user nice system idle iowait  irq  softirq steal guest guest_nicecpu  4705 356  584    3699   23    23     0       0     00cpu0 1393280 32966 572056 13343292 6130 0 17875 0 23933 0   The amount of time, measured in units of USER_HZ   (1/100ths of a second on most architectures, use   sysconf(_SC_CLK_TCK) to obtain the right value), that   the system ("cpu" line) or the specific CPU ("cpuN"   line) spent in various states:   user   (1) Time spent in user mode.   nice   (2) Time spent in user mode with low priority  (nice).   system (3) Time spent in system mode.   idle   (4) Time spent in the idle task.  This value  should be USER_HZ times the second entry in the  /proc/uptime pseudo-file.   iowait (since Linux 2.5.41)  (5) Time waiting for I/O to complete.  This  value is not reliable, for the following rea‐  sons:  1. The CPU will not wait for I/O to complete;     iowait is the time that a task is waiting for     I/O to complete.  When a CPU goes into idle     state for outstanding task I/O, another task     will be scheduled on this CPU.  2. On a multi-core CPU, the task waiting for I/O     to complete is not running on any CPU, so the     iowait of each CPU is difficult to calculate.  3. The value in this field may decrease in cer‐     tain conditions.   irq (since Linux 2.6.0-test4)  (6) Time servicing interrupts.   softirq (since Linux 2.6.0-test4)  (7) Time servicing softirqs.   steal (since Linux 2.6.11)  (8) Stolen time, which is the time spent in  other operating systems when running in a virtu‐  alized environment   guest (since Linux 2.6.24)  (9) Time spent running a virtual CPU for guest  operating systems under the control of the Linux  kernel.   guest_nice (since Linux 2.6.33)  (10) Time spent running a niced guest (virtual  CPU for guest operating systems under the con‐  trol of the Linux kernel).

2.計算具體CPU使用率

有了上面的背景知識,接下來我們就可以計算具體CPU的使用情況了。具體計算方式如下:

Total CPU time since boot = user+nice+system+idle+iowait+irq+softirq+stealTotal CPU Idle time since boot = idle + iowaitTotal CPU usage time since boot = Total CPU time since boot - Total CPU Idle time since bootTotal CPU percentage = Total CPU usage time since boot/Total CPU time since boot * 100%

有了上面的計算公式,計算某一CPU使用率或者系統(tǒng)總的CPU占用率也就是不難了。
示例:計算系統(tǒng)整體CPU占用情況
首先從/proc/stat中獲取 t1時刻系統(tǒng)總體的user、nice、system、idle、iowait、irq、softirq、steal、guest、guest_nice的值,得到此時Total CPU time since boot(記為total1)和 Total CPU idle time since boot(記為idle1)。
其次,從/proc/stat中獲取t2時刻系統(tǒng)總的Total CPU time since boot(記為total2)和Total CPU idle time since boot(記為idle2)。(方法同上一步)
最后,計算t2t1之間系統(tǒng)總的CPU使用情況。也就是:
CPU percentage between t1 and t2 = ((total2-total1)-(idle2-idle1))/(total2-total1)* 100%
其中, ((total2-total1)-(idle2-idle1))實際上就是t1與t2時刻之間系統(tǒng)CPU被占用的時間(總時間 - 空閑時間)。
下面是一段計算時間段內(nèi)CPU被占用情況的腳本:

#!/bin/bash# by Paul Colby (http://colby.id.au), no rights reserved ;)PREV_TOTAL=0PREV_IDLE=0while true; do  # Get the total CPU statistics, discarding the "cpu " prefix.  CPU=(`sed -n "s/^cpu\s//p" /proc/stat`)  IDLE=${CPU[3]} # Just the idle CPU time.  # Calculate the total CPU time.  TOTAL=0  for VALUE in "${CPU[@]}"; do    let "TOTAL=$TOTAL+$VALUE"  done  # Calculate the CPU usage since we last checked.  let "DIFF_IDLE=$IDLE-$PREV_IDLE"  let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"  let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"  echo -en "\rCPU: $DIFF_USAGE%  \b\b"  # Remember the total and idle CPU times for the next check.  PREV_TOTAL="$TOTAL"  PREV_IDLE="$IDLE"  # Wait before checking again.  sleep 1done

拓展

在內(nèi)核中,關(guān)于/proc/stat中文件的實現(xiàn)函數(shù)如下:

附注:內(nèi)核版本3.14.69,文件為 /fs/proc/stat.c#include <linux/cpumask.h>#include <linux/fs.h>#include <linux/init.h>#include <linux/interrupt.h>#include <linux/kernel_stat.h>#include <linux/proc_fs.h>#include <linux/sched.h>#include <linux/seq_file.h>#include <linux/slab.h>#include <linux/time.h>#include <linux/irqnr.h>#include <asm/cputime.h>#include <linux/tick.h>#ifndef arch_irq_stat_cpu#define arch_irq_stat_cpu(cpu) 0#endif#ifndef arch_irq_stat#define arch_irq_stat() 0#endif#ifdef arch_idle_timestatic cputime64_t get_idle_time(int cpu){	cputime64_t idle;	idle = kcpustat_cpu(cpu).cpustat[CPUTIME_IDLE];	if (cpu_online(cpu) && !nr_iowait_cpu(cpu))		idle += arch_idle_time(cpu);	return idle;}static cputime64_t get_iowait_time(int cpu){	cputime64_t iowait;	iowait = kcpustat_cpu(cpu).cpustat[CPUTIME_IOWAIT];	if (cpu_online(cpu) && nr_iowait_cpu(cpu))		iowait += arch_idle_time(cpu);	return iowait;}#elsestatic u64 get_idle_time(int cpu){	u64 idle, idle_time = -1ULL;	if (cpu_online(cpu))		idle_time = get_cpu_idle_time_us(cpu, NULL);	if (idle_time == -1ULL)		/* !NO_HZ or cpu offline so we can rely on cpustat.idle */		idle = kcpustat_cpu(cpu).cpustat[CPUTIME_IDLE];	else		idle = usecs_to_cputime64(idle_time);	return idle;}static u64 get_iowait_time(int cpu){	u64 iowait, iowait_time = -1ULL;	if (cpu_online(cpu))		iowait_time = get_cpu_iowait_time_us(cpu, NULL);	if (iowait_time == -1ULL)		/* !NO_HZ or cpu offline so we can rely on cpustat.iowait */		iowait = kcpustat_cpu(cpu).cpustat[CPUTIME_IOWAIT];	else		iowait = usecs_to_cputime64(iowait_time);	return iowait;}#endifstatic int show_stat(struct seq_file *p, void *v){	int i, j;	unsigned long jif;	u64 user, nice, system, idle, iowait, irq, softirq, steal;	u64 guest, guest_nice;	u64 sum = 0;	u64 sum_softirq = 0;	unsigned int per_softirq_sums[NR_SOFTIRQS] = {0};	struct timespec boottime;	user = nice = system = idle = iowait =		irq = softirq = steal = 0;	guest = guest_nice = 0;	getboottime(&boottime);	jif = boottime.tv_sec;	for_each_possible_cpu(i) {		user += kcpustat_cpu(i).cpustat[CPUTIME_USER];		nice += kcpustat_cpu(i).cpustat[CPUTIME_NICE];		system += kcpustat_cpu(i).cpustat[CPUTIME_SYSTEM];		idle += get_idle_time(i);		iowait += get_iowait_time(i);		irq += kcpustat_cpu(i).cpustat[CPUTIME_IRQ];		softirq += kcpustat_cpu(i).cpustat[CPUTIME_SOFTIRQ];		steal += kcpustat_cpu(i).cpustat[CPUTIME_STEAL];		guest += kcpustat_cpu(i).cpustat[CPUTIME_GUEST];		guest_nice += kcpustat_cpu(i).cpustat[CPUTIME_GUEST_NICE];		sum += kstat_cpu_irqs_sum(i);		sum += arch_irq_stat_cpu(i);		for (j = 0; j < NR_SOFTIRQS; j++) {			unsigned int softirq_stat = kstat_softirqs_cpu(j, i);			per_softirq_sums[j] += softirq_stat;			sum_softirq += softirq_stat;		}	}	sum += arch_irq_stat();	seq_puts(p, "cpu ");	seq_put_decimal_ull(p, " ", cputime64_to_clock_t(user));	seq_put_decimal_ull(p, " ", cputime64_to_clock_t(nice));	seq_put_decimal_ull(p, " ", cputime64_to_clock_t(system));	seq_put_decimal_ull(p, " ", cputime64_to_clock_t(idle));	seq_put_decimal_ull(p, " ", cputime64_to_clock_t(iowait));	seq_put_decimal_ull(p, " ", cputime64_to_clock_t(irq));	seq_put_decimal_ull(p, " ", cputime64_to_clock_t(softirq));	seq_put_decimal_ull(p, " ", cputime64_to_clock_t(steal));	seq_put_decimal_ull(p, " ", cputime64_to_clock_t(guest));	seq_put_decimal_ull(p, " ", cputime64_to_clock_t(guest_nice));	seq_putc(p, "\n");	for_each_online_cpu(i) {		/* Copy values here to work around gcc-2.95.3, gcc-2.96 */		user = kcpustat_cpu(i).cpustat[CPUTIME_USER];		nice = kcpustat_cpu(i).cpustat[CPUTIME_NICE];		system = kcpustat_cpu(i).cpustat[CPUTIME_SYSTEM];		idle = get_idle_time(i);		iowait = get_iowait_time(i);		irq = kcpustat_cpu(i).cpustat[CPUTIME_IRQ];		softirq = kcpustat_cpu(i).cpustat[CPUTIME_SOFTIRQ];		steal = kcpustat_cpu(i).cpustat[CPUTIME_STEAL];		guest = kcpustat_cpu(i).cpustat[CPUTIME_GUEST];		guest_nice = kcpustat_cpu(i).cpustat[CPUTIME_GUEST_NICE];		seq_printf(p, "cpu%d", i);		seq_put_decimal_ull(p, " ", cputime64_to_clock_t(user));		seq_put_decimal_ull(p, " ", cputime64_to_clock_t(nice));		seq_put_decimal_ull(p, " ", cputime64_to_clock_t(system));		seq_put_decimal_ull(p, " ", cputime64_to_clock_t(idle));		seq_put_decimal_ull(p, " ", cputime64_to_clock_t(iowait));		seq_put_decimal_ull(p, " ", cputime64_to_clock_t(irq));		seq_put_decimal_ull(p, " ", cputime64_to_clock_t(softirq));		seq_put_decimal_ull(p, " ", cputime64_to_clock_t(steal));		seq_put_decimal_ull(p, " ", cputime64_to_clock_t(guest));		seq_put_decimal_ull(p, " ", cputime64_to_clock_t(guest_nice));		seq_putc(p, "\n");	}	seq_printf(p, "intr %llu", (unsigned long long)sum);	/* sum again ? it could be updated? */	for_each_irq_nr(j)		seq_put_decimal_ull(p, " ", kstat_irqs_usr(j));	seq_printf(p,		"\nctxt %llu\n"		"btime %lu\n"		"processes %lu\n"		"procs_running %lu\n"		"procs_blocked %lu\n",		nr_context_switches(),		(unsigned long)jif,		total_forks,		nr_running(),		nr_iowait());	seq_printf(p, "softirq %llu", (unsigned long long)sum_softirq);	for (i = 0; i < NR_SOFTIRQS; i++)		seq_put_decimal_ull(p, " ", per_softirq_sums[i]);	seq_putc(p, "\n");	return 0;}static int stat_open(struct inode *inode, struct file *file){	size_t size = 1024 + 128 * num_possible_cpus();	char *buf;	struct seq_file *m;	int res;	/* minimum size to display an interrupt count : 2 bytes */	size += 2 * nr_irqs;	/* don"t ask for more than the kmalloc() max size */	if (size > KMALLOC_MAX_SIZE)		size = KMALLOC_MAX_SIZE;	buf = kmalloc(size, GFP_KERNEL);	if (!buf)		return -ENOMEM;	res = single_open(file, show_stat, NULL);	if (!res) {		m = file->private_data;		m->buf = buf;		m->size = ksize(buf);	} else		kfree(buf);	return res;}static const struct file_operations proc_stat_operations = {	.open		= stat_open,	.read		= seq_read,	.llseek		= seq_lseek,	.release	= single_release,};static int __init proc_stat_init(void){	proc_create("stat", 0, NULL, &proc_stat_operations);	return 0;}fs_initcall(proc_stat_init);

參考

到此這篇關(guān)于Linux中計算特定CPU使用率案例詳解的文章就介紹到這了,更多相關(guān)Linux中計算特定CPU使用率內(nèi)容請搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持!

主站蜘蛛池模板: 中图网(原中国图书网):网上书店,尾货特色书店,30万种特价书低至2折! | 304不锈钢无缝管_不锈钢管厂家 - 隆达钢业集团有限公司 | 半容积式换热器_北京浮动盘管换热器厂家|北京亿丰上达 | 绿萝净除甲醛|深圳除甲醛公司|测甲醛怎么收费|培训机构|电影院|办公室|车内|室内除甲醛案例|原理|方法|价格立马咨询 | 金现代信息产业股份有限公司--数字化解决方案供应商 | 江西自考网-江西自学考试网| 连栋温室大棚建造厂家-智能玻璃温室-薄膜温室_青州市亿诚农业科技 | 干式变压器厂_干式变压器厂家_scb11/scb13/scb10/scb14/scb18干式变压器生产厂家-山东科锐变压器有限公司 | 蓄电池回收,ups电池后备电源回收,铅酸蓄电池回收,机房电源回收-广州益夫铅酸电池回收公司 | 电表箱-浙江迈峰电力设备有限公司-电表箱专业制造商 | 长沙一级消防工程公司_智能化弱电_机电安装_亮化工程专业施工承包_湖南公共安全工程有限公司 | 一体化污水处理设备,一体化污水设备厂家-宜兴市福源水处理设备有限公司 | 淘气堡_室内儿童乐园_户外无动力儿童游乐设备-高乐迪(北京) | 铸铁平台,大理石平台专业生产厂家_河北-北重机械 | 自动记录数据电子台秤,记忆储存重量电子桌称,设定时间记录电子秤-昆山巨天 | 单锥双螺旋混合机_双螺旋锥形混合机-无锡新洋设备科技有限公司 | 无菌检查集菌仪,微生物限度仪器-苏州长留仪器百科 | 合肥制氮机_合肥空压机厂家_安徽真空泵-凯圣精机 | SPC工作站-连杆综合检具-表盘气动量仪-内孔缺陷检测仪-杭州朗多检测仪器有限公司 | 伸缩器_伸缩接头_传力接头-巩义市润达管道设备制造有限公司 | 苏州西装定制-西服定制厂家-职业装定制厂家-尺品服饰西装定做公司 | 日本细胞免疫疗法_肿瘤免疫治疗_NK细胞疗法 - 免疫密码 | 厚壁钢管-厚壁无缝钢管-小口径厚壁钢管-大口径厚壁钢管 - 聊城宽达钢管有限公司 | 防堵吹扫装置-防堵风压测量装置-电动操作显示器-兴洲仪器 | 深圳网站建设-高端企业网站开发-定制网页设计制作公司 | sus630/303cu不锈钢棒,440C/430F/17-4ph不锈钢研磨棒-江苏德镍金属科技有限公司 | 扒渣机,铁水扒渣机,钢水扒渣机,铁水捞渣机,钢水捞渣机-烟台盛利达工程技术有限公司 | LNG鹤管_内浮盘价格,上装鹤管,装车撬厂家-连云港赛威特机械 | 珠宝展柜-玻璃精品展柜-首饰珠宝展示柜定制-鸿钛展柜厂家 | 贴片电容代理-三星电容-村田电容-风华电容-国巨电容-深圳市昂洋科技有限公司 | 武汉天安盾电子设备有限公司 - 安盾安检,武汉安检门,武汉安检机,武汉金属探测器,武汉测温安检门,武汉X光行李安检机,武汉防爆罐,武汉车底安全检查,武汉液体探测仪,武汉安检防爆设备 | 润东方环保空调,冷风机,厂房车间降温设备-20年深圳环保空调生产厂家 | 精密光学实验平台-红外粉末压片机模具-天津博君 | 全自动贴标机-套标机-工业热风机-不干胶贴标机-上海厚冉机械 | 匀胶机旋涂仪-声扫显微镜-工业水浸超声-安赛斯(北京)科技有限公司 | 西门子气候补偿器,锅炉气候补偿器-陕西沃信机电工程有限公司 | 恒温恒湿箱(药品/保健品/食品/半导体/细菌)-兰贝石(北京)科技有限公司 | 东莞精密模具加工,精密连接器模具零件,自動機零件,冶工具加工-益久精密 | 酒糟烘干机-豆渣烘干机-薯渣烘干机-糟渣烘干设备厂家-焦作市真节能环保设备科技有限公司 | 天津蒸汽/热水锅炉-电锅炉安装维修直销厂家-天津鑫淼暖通设备有限公司 | 阳光模拟试验箱_高低温试验箱_高低温冲击试验箱_快速温变试验箱|东莞市赛思检测设备有限公司 |