Created
August 3, 2017 15:44
-
-
Save ishiy1993/8b871398f7ae44b259d2163b5dba05d7 to your computer and use it in GitHub Desktop.
Display CPU and Memory usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import sys | |
import time | |
def read_cpu_info(): | |
with open("/proc/stat", 'r') as f: | |
cpu = next(f).split(' ') | |
cpu_busy = sum([int(b) for b in cpu[2:5]]) | |
cpu_total = cpu_busy + int(cpu[5]) | |
return (cpu_total, cpu_busy) | |
def get_cpu_percent(t): | |
t1, b1 = read_cpu_info() | |
time.sleep(t) | |
t2, b2 = read_cpu_info() | |
if b2 <= b1: | |
return 0.0 | |
try: | |
cpu_perc = 100*(b2-b1)/(t2-t1) | |
except: | |
return 0.0 | |
else: | |
return cpu_perc | |
def get_memory_percent(): | |
with open("/proc/meminfo", 'r') as f: | |
total = int(next(f).split(' ')[-2]) | |
next(f) | |
available = int(next(f).split(' ')[-2]) | |
return 100*(1-available/total); | |
def main(): | |
if len(sys.argv) > 1: | |
t = float(sys.argv[1]) | |
else: | |
t = 0.1 | |
try: | |
cpu_perc = get_cpu_percent(t) | |
mem_perc = get_memory_percent() | |
except: | |
print("Unable to get system info...") | |
exit(1) | |
print("%3d%%:%3d%%" % (cpu_perc, mem_perc)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
CPU使用率の計測のためのインターバルを引数で指定できる。
デフォルトでは 0.1 secになっている。