python和bash统计CPU利用率的方法

WBOY
Release: 2016-06-10 15:09:36
Original
1248 people have browsed it

本文实例讲述了python和bash统计CPU利用率的方法。分享给大家供大家参考。具体如下:

开始的时候写了一个 bash 的实现;
因为最近也在学习 python ,所以就尝试着用 python 再实现一回;
支援 python2 环境;
请各位给予下建议,有什么改良的地方可以提一下,不甚感激;

Python代码如下:

#!/usr/bin/python
# -*- coding:utf8 -*-
__author__ = 'chenwx'
def cpu_rate():
  import time
  def cpu_r():
    f = open("/proc/stat","r")
    for f_line in f:
      break
    f.close()
    f_line = f_line.split(" ")
    f_line_a=[]
    for i in f_line:
      if i.isdigit():
        i=int(i)
        f_line_a.append(i)
    total = sum(f_line_a)
    idle = f_line_a[3]
    return total,idle
  total_a,idle_a=cpu_r()
  time.sleep(2)
  total_b,idle_b=cpu_r()
  sys_idle = idle_b - idle_a
  sys_total = total_b - total_a
  sys_us = sys_total - sys_idle
  cpu_a = (float(sys_us)/sys_total)*100
  return cpu_a
# print cpu_rate()

Copy after login

bash的实现方式:

#!/bin/bash
# 感觉计算数组这里应该还有办法简化的吧;
# 我一时没想到,请大家提一下建议,多谢;
cpu_a=(`grep 'cpu ' /proc/stat`)
total_a=$((${cpu_a[1]}+${cpu_a[2]}+${cpu_a[3]}+${cpu_a[4]}+${cpu_a[5]}+${cpu_a[6]}+${cpu_a[7]}+${cpu_a[8]}+${cpu_a[9]}))
idle_a=${cpu_a[4]}
sleep 5
cpu_b=(`grep 'cpu ' /proc/stat`)
total_b=$((${cpu_b[1]}+${cpu_b[2]}+${cpu_b[3]}+${cpu_b[4]}+${cpu_b[5]}+${cpu_b[6]}+${cpu_b[7]}+${cpu_b[8]}+${cpu_b[9]}))
idle_b=${cpu_b[4]}
sys_idle=$(($idle_b-$idle_a))
sys_total=$(($total_b-$total_a))
sys_us=$(($sys_total-$sys_idle))
echo "scale=2;$sys_us/$sys_total*100" | bc

Copy after login

遍历数组的方法:

# 找到了解决数组计算的办法了,不过感觉for循环计算的方式还是有些繁琐;
# 不知道有没有那种对数组内所有值一并计算的方法;
cpu_rate_a () {
cpu_a=(`grep 'cpu ' /proc/stat`)
for i in ${cpu_a[@]:1}
do
  total_a=$(($total_a+$i))
done
idle_a=${cpu_a[4]}
sleep 5
cpu_b=(`grep 'cpu ' /proc/stat`)
for i in ${cpu_b[@]:1}
do
  total_b=$(($total_b+$i))
done
idle_b=${cpu_b[4]}
sys_idle=$(($idle_b-$idle_a))
sys_total=$(($total_b-$total_a))
sys_us=$(($sys_total-$sys_idle))
local_cpu_rate=$(echo "scale=2;$sys_us/$sys_total*100" | bc)
}

Copy after login

希望本文所述对大家的Python程序设计有所帮助。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!