设为首页收藏本站

安徽论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 11196|回复: 0

Linux中计算特定CPU使用率案例详解

[复制链接]

85

主题

0

回帖

267

积分

中级会员

Rank: 3Rank: 3

积分
267
发表于 2022-3-26 11:03:08 | 显示全部楼层 |阅读模式
网站内容均来自网络,本站只提供信息平台,如有侵权请联系删除,谢谢!
Linux中计算特定CPU使用率 需求解决方案拓展参考
需求

在Linux中可以通过top指令查看某一进程占用的CPU情况,也可以查看某一个CPU使用率情况(先top指令,然后按数字“1”键即可显示每一个CPU的使用情况),如下图:

而我们的需求是:如何得到一个CPU的占用率呢?
解决方案

1. 背景知识
在/proc/stat中可以查看每一个CPU的使用情况的,如下图:

其中cpu(0/1/2/…)后面的那十个数字含义如下:
  1. /proc/stat
  2. kernel/system statistics.  Varies with architecture.  
  3. Common entries include:

  4.      user nice system idle iowait  irq  softirq steal guest guest_nice
  5. cpu  4705 356  584    3699   23    23     0       0     0        0
  6. cpu0 1393280 32966 572056 13343292 6130 0 17875 0 23933 0
  7.    The amount of time, measured in units of USER_HZ
  8.    (1/100ths of a second on most architectures, use
  9.    sysconf(_SC_CLK_TCK) to obtain the right value), that
  10.    the system ("cpu" line) or the specific CPU ("cpuN"
  11.    line) spent in various states:

  12.    user   (1) Time spent in user mode.

  13.    nice   (2) Time spent in user mode with low priority
  14.           (nice).

  15.    system (3) Time spent in system mode.

  16.    idle   (4) Time spent in the idle task.  This value
  17.           should be USER_HZ times the second entry in the
  18.           /proc/uptime pseudo-file.

  19.    iowait (since Linux 2.5.41)
  20.           (5) Time waiting for I/O to complete.  This
  21.           value is not reliable, for the following rea‐
  22.           sons:

  23.           1. The CPU will not wait for I/O to complete;
  24.              iowait is the time that a task is waiting for
  25.              I/O to complete.  When a CPU goes into idle
  26.              state for outstanding task I/O, another task
  27.              will be scheduled on this CPU.

  28.           2. On a multi-core CPU, the task waiting for I/O
  29.              to complete is not running on any CPU, so the
  30.              iowait of each CPU is difficult to calculate.

  31.           3. The value in this field may decrease in cer‐
  32.              tain conditions.

  33.    irq (since Linux 2.6.0-test4)
  34.           (6) Time servicing interrupts.

  35.    softirq (since Linux 2.6.0-test4)
  36.           (7) Time servicing softirqs.

  37.    steal (since Linux 2.6.11)
  38.           (8) Stolen time, which is the time spent in
  39.           other operating systems when running in a virtu‐
  40.           alized environment

  41.    guest (since Linux 2.6.24)
  42.           (9) Time spent running a virtual CPU for guest
  43.           operating systems under the control of the Linux
  44.           kernel.

  45.    guest_nice (since Linux 2.6.33)
  46.           (10) Time spent running a niced guest (virtual
  47.           CPU for guest operating systems under the con‐
  48.           trol of the Linux kernel).
复制代码
2.计算具体CPU使用率
有了上面的背景知识,接下来我们就可以计算具体CPU的使用情况了。具体计算方式如下:
  1. Total CPU time since boot = user+nice+system+idle+iowait+irq+softirq+steal
  2. Total CPU Idle time since boot = idle + iowait
  3. Total CPU usage time since boot = Total CPU time since boot - Total CPU Idle time since boot
  4. Total CPU percentage = Total CPU usage time since boot/Total CPU time since boot * 100%
复制代码
有了上面的计算公式,计算某一CPU使用率或者系统总的CPU占用率也就是不难了。
示例:计算系统整体CPU占用情况
首先从/proc/stat中获取 t1时刻系统总体的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时刻系统总的Total CPU time since boot(记为total2)和Total CPU idle time since boot(记为idle2)。(方法同上一步)
最后,计算t2t1之间系统总的CPU使用情况。也就是:
CPU percentage between t1 and t2 = ((total2-total1)-(idle2-idle1))/(total2-total1)* 100%
其中, ((total2-total1)-(idle2-idle1))实际上就是t1与t2时刻之间系统CPU被占用的时间(总时间 - 空闲时间)。
下面是一段计算时间段内CPU被占用情况的脚本:
  1. #!/bin/bash
  2. # by Paul Colby (http://colby.id.au), no rights reserved ;)

  3. PREV_TOTAL=0
  4. PREV_IDLE=0

  5. while true; do
  6.   # Get the total CPU statistics, discarding the 'cpu ' prefix.
  7.   CPU=(`sed -n 's/^cpu\s//p' /proc/stat`)
  8.   IDLE=${CPU[3]} # Just the idle CPU time.

  9.   # Calculate the total CPU time.
  10.   TOTAL=0
  11.   for VALUE in "${CPU[@]}"; do
  12.     let "TOTAL=$TOTAL+$VALUE"
  13.   done

  14.   # Calculate the CPU usage since we last checked.
  15.   let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  16.   let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  17.   let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"
  18.   echo -en "\rCPU: $DIFF_USAGE%  \b\b"

  19.   # Remember the total and idle CPU times for the next check.
  20.   PREV_TOTAL="$TOTAL"
  21.   PREV_IDLE="$IDLE"

  22.   # Wait before checking again.
  23.   sleep 1
  24. done
复制代码
拓展

在内核中,关于/proc/stat中文件的实现函数如下:
  1. 附注:内核版本3.14.69,文件为 /fs/proc/stat.c

  2. #include <linux/cpumask.h>
  3. #include <linux/fs.h>
  4. #include <linux/init.h>
  5. #include <linux/interrupt.h>
  6. #include <linux/kernel_stat.h>
  7. #include <linux/proc_fs.h>
  8. #include <linux/sched.h>
  9. #include <linux/seq_file.h>
  10. #include <linux/slab.h>
  11. #include <linux/time.h>
  12. #include <linux/irqnr.h>
  13. #include <asm/cputime.h>
  14. #include <linux/tick.h>

  15. #ifndef arch_irq_stat_cpu
  16. #define arch_irq_stat_cpu(cpu) 0
  17. #endif
  18. #ifndef arch_irq_stat
  19. #define arch_irq_stat() 0
  20. #endif

  21. #ifdef arch_idle_time

  22. static cputime64_t get_idle_time(int cpu)
  23. {
  24.         cputime64_t idle;

  25.         idle = kcpustat_cpu(cpu).cpustat[CPUTIME_IDLE];
  26.         if (cpu_online(cpu) && !nr_iowait_cpu(cpu))
  27.                 idle += arch_idle_time(cpu);
  28.         return idle;
  29. }

  30. static cputime64_t get_iowait_time(int cpu)
  31. {
  32.         cputime64_t iowait;

  33.         iowait = kcpustat_cpu(cpu).cpustat[CPUTIME_IOWAIT];
  34.         if (cpu_online(cpu) && nr_iowait_cpu(cpu))
  35.                 iowait += arch_idle_time(cpu);
  36.         return iowait;
  37. }

  38. #else

  39. static u64 get_idle_time(int cpu)
  40. {
  41.         u64 idle, idle_time = -1ULL;

  42.         if (cpu_online(cpu))
  43.                 idle_time = get_cpu_idle_time_us(cpu, NULL);

  44.         if (idle_time == -1ULL)
  45.                 /* !NO_HZ or cpu offline so we can rely on cpustat.idle */
  46.                 idle = kcpustat_cpu(cpu).cpustat[CPUTIME_IDLE];
  47.         else
  48.                 idle = usecs_to_cputime64(idle_time);

  49.         return idle;
  50. }

  51. static u64 get_iowait_time(int cpu)
  52. {
  53.         u64 iowait, iowait_time = -1ULL;

  54.         if (cpu_online(cpu))
  55.                 iowait_time = get_cpu_iowait_time_us(cpu, NULL);

  56.         if (iowait_time == -1ULL)
  57.                 /* !NO_HZ or cpu offline so we can rely on cpustat.iowait */
  58.                 iowait = kcpustat_cpu(cpu).cpustat[CPUTIME_IOWAIT];
  59.         else
  60.                 iowait = usecs_to_cputime64(iowait_time);

  61.         return iowait;
  62. }

  63. #endif

  64. static int show_stat(struct seq_file *p, void *v)
  65. {
  66.         int i, j;
  67.         unsigned long jif;
  68.         u64 user, nice, system, idle, iowait, irq, softirq, steal;
  69.         u64 guest, guest_nice;
  70.         u64 sum = 0;
  71.         u64 sum_softirq = 0;
  72.         unsigned int per_softirq_sums[NR_SOFTIRQS] = {0};
  73.         struct timespec boottime;

  74.         user = nice = system = idle = iowait =
  75.                 irq = softirq = steal = 0;
  76.         guest = guest_nice = 0;
  77.         getboottime(&boottime);
  78.         jif = boottime.tv_sec;

  79.         for_each_possible_cpu(i) {
  80.                 user += kcpustat_cpu(i).cpustat[CPUTIME_USER];
  81.                 nice += kcpustat_cpu(i).cpustat[CPUTIME_NICE];
  82.                 system += kcpustat_cpu(i).cpustat[CPUTIME_SYSTEM];
  83.                 idle += get_idle_time(i);
  84.                 iowait += get_iowait_time(i);
  85.                 irq += kcpustat_cpu(i).cpustat[CPUTIME_IRQ];
  86.                 softirq += kcpustat_cpu(i).cpustat[CPUTIME_SOFTIRQ];
  87.                 steal += kcpustat_cpu(i).cpustat[CPUTIME_STEAL];
  88.                 guest += kcpustat_cpu(i).cpustat[CPUTIME_GUEST];
  89.                 guest_nice += kcpustat_cpu(i).cpustat[CPUTIME_GUEST_NICE];
  90.                 sum += kstat_cpu_irqs_sum(i);
  91.                 sum += arch_irq_stat_cpu(i);

  92.                 for (j = 0; j < NR_SOFTIRQS; j++) {
  93.                         unsigned int softirq_stat = kstat_softirqs_cpu(j, i);

  94.                         per_softirq_sums[j] += softirq_stat;
  95.                         sum_softirq += softirq_stat;
  96.                 }
  97.         }
  98.         sum += arch_irq_stat();

  99.         seq_puts(p, "cpu ");
  100.         seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(user));
  101.         seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(nice));
  102.         seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(system));
  103.         seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(idle));
  104.         seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(iowait));
  105.         seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(irq));
  106.         seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(softirq));
  107.         seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(steal));
  108.         seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(guest));
  109.         seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(guest_nice));
  110.         seq_putc(p, '\n');

  111.         for_each_online_cpu(i) {
  112.                 /* Copy values here to work around gcc-2.95.3, gcc-2.96 */
  113.                 user = kcpustat_cpu(i).cpustat[CPUTIME_USER];
  114.                 nice = kcpustat_cpu(i).cpustat[CPUTIME_NICE];
  115.                 system = kcpustat_cpu(i).cpustat[CPUTIME_SYSTEM];
  116.                 idle = get_idle_time(i);
  117.                 iowait = get_iowait_time(i);
  118.                 irq = kcpustat_cpu(i).cpustat[CPUTIME_IRQ];
  119.                 softirq = kcpustat_cpu(i).cpustat[CPUTIME_SOFTIRQ];
  120.                 steal = kcpustat_cpu(i).cpustat[CPUTIME_STEAL];
  121.                 guest = kcpustat_cpu(i).cpustat[CPUTIME_GUEST];
  122.                 guest_nice = kcpustat_cpu(i).cpustat[CPUTIME_GUEST_NICE];
  123.                 seq_printf(p, "cpu%d", i);
  124.                 seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(user));
  125.                 seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(nice));
  126.                 seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(system));
  127.                 seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(idle));
  128.                 seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(iowait));
  129.                 seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(irq));
  130.                 seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(softirq));
  131.                 seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(steal));
  132.                 seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(guest));
  133.                 seq_put_decimal_ull(p, ' ', cputime64_to_clock_t(guest_nice));
  134.                 seq_putc(p, '\n');
  135.         }
  136.         seq_printf(p, "intr %llu", (unsigned long long)sum);

  137.         /* sum again ? it could be updated? */
  138.         for_each_irq_nr(j)
  139.                 seq_put_decimal_ull(p, ' ', kstat_irqs_usr(j));

  140.         seq_printf(p,
  141.                 "\nctxt %llu\n"
  142.                 "btime %lu\n"
  143.                 "processes %lu\n"
  144.                 "procs_running %lu\n"
  145.                 "procs_blocked %lu\n",
  146.                 nr_context_switches(),
  147.                 (unsigned long)jif,
  148.                 total_forks,
  149.                 nr_running(),
  150.                 nr_iowait());

  151.         seq_printf(p, "softirq %llu", (unsigned long long)sum_softirq);

  152.         for (i = 0; i < NR_SOFTIRQS; i++)
  153.                 seq_put_decimal_ull(p, ' ', per_softirq_sums[i]);
  154.         seq_putc(p, '\n');

  155.         return 0;
  156. }

  157. static int stat_open(struct inode *inode, struct file *file)
  158. {
  159.         size_t size = 1024 + 128 * num_possible_cpus();
  160.         char *buf;
  161.         struct seq_file *m;
  162.         int res;

  163.         /* minimum size to display an interrupt count : 2 bytes */
  164.         size += 2 * nr_irqs;

  165.         /* don't ask for more than the kmalloc() max size */
  166.         if (size > KMALLOC_MAX_SIZE)
  167.                 size = KMALLOC_MAX_SIZE;
  168.         buf = kmalloc(size, GFP_KERNEL);
  169.         if (!buf)
  170.                 return -ENOMEM;

  171.         res = single_open(file, show_stat, NULL);
  172.         if (!res) {
  173.                 m = file->private_data;
  174.                 m->buf = buf;
  175.                 m->size = ksize(buf);
  176.         } else
  177.                 kfree(buf);
  178.         return res;
  179. }

  180. static const struct file_operations proc_stat_operations = {
  181.         .open                = stat_open,
  182.         .read                = seq_read,
  183.         .llseek                = seq_lseek,
  184.         .release        = single_release,
  185. };

  186. static int __init proc_stat_init(void)
  187. {
  188.         proc_create("stat", 0, NULL, &proc_stat_operations);
  189.         return 0;
  190. }
  191. fs_initcall(proc_stat_init);
复制代码
参考

http://man7.org/linux/man-pages/man5/proc.5.html
https://github.com/pcolby/scripts/blob/master/cpu.sh
https://elixir.bootlin.com/linux/v3.14.69/source/fs/proc/stat.c
到此这篇关于Linux中计算特定CPU使用率案例详解的文章就介绍到这了,更多相关Linux中计算特定CPU使用率内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!
                                                                                               
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
免责声明
1. 本论坛所提供的信息均来自网络,本网站只提供平台服务,所有账号发表的言论与本网站无关。
2. 其他单位或个人在使用、转载或引用本文时,必须事先获得该帖子作者和本人的同意。
3. 本帖部分内容转载自其他媒体,但并不代表本人赞同其观点和对其真实性负责。
4. 如有侵权,请立即联系,本网站将及时删除相关内容。
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表