-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpusingle.py
70 lines (56 loc) · 1.72 KB
/
cpusingle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python
import sys
import os
import time
import subprocess
if len(sys.argv) == 2:
pid = sys.argv[1]
else:
print('No PID specified. Usage: %s <PID>' % os.path.basename(__file__))
sys.exit(1)
def proct(pid):
try:
with open(os.path.join('/proc/', pid, 'stat'), 'r') as pidfile:
proctimes = pidfile.readline()
# get utime from /proc/<pid>/stat, 14 item
utime = proctimes.split(' ')[13]
# get stime from proc/<pid>/stat, 15 item
stime = proctimes.split(' ')[14]
# count total process used time
proctotal = int(utime) + int(stime)
return(float(proctotal))
except IOError as e:
print('ERROR: %s' % e)
sys.exit(2)
def cput():
try:
with open('/proc/stat', 'r') as procfile:
cputimes = procfile.readline()
cputotal = 0
# count from /proc/stat: user, nice, system, idle, iowait, irc, softirq, steal, guest
for i in cputimes.split(' ')[2:]:
i = int(i)
cputotal = (cputotal + i)
return(float(cputotal))
except IOError as e:
print('ERROR: %s' % e)
sys.exit(3)
# assign start values before loop them
proctotal = proct(pid)
cputotal = cput()
try:
while True:
pr_proctotal = proctotal
pr_cputotal = cputotal
proctotal = proct(pid)
cputotal = cput()
try:
t = time.ctime()
res = ((proctotal - pr_proctotal) / (cputotal - pr_cputotal) * 100)
load = round(res, 1)
print ("%s\t%s" % (t,load))
except ZeroDivisionError:
pass
time.sleep(1)
except KeyboardInterrupt:
sys.exit(0)