Skip to content

Instantly share code, notes, and snippets.

@piotrmaslanka
Created July 18, 2013 21:18
Show Gist options
  • Save piotrmaslanka/6033175 to your computer and use it in GitHub Desktop.
Save piotrmaslanka/6033175 to your computer and use it in GitHub Desktop.
A simple tool to track CPU usage of given process
"""
A simple process to measure CPU usage of a process during specified time
Requires at least Linux 2.6.
Care with measurement on tickless kernels!
"""
from __future__ import division
import sys, time
if len(sys.argv) != 4:
sys.stderr.write('''Proper usage:
python tukan.py <PID> <DELAY> <TIMES>
<PID>: PID of process to monitor
<DELAY>: (float) amount of seconds of polling interval
<TIMES>: amount of times to poll
Output is dumped on stdout. Each line is a float, percentage
of single processor usage without the percent sign
''')
sys.exit()
def get_params(pid):
"""Returns a tuple:
(utime+stime for PID, time_total for system)"""
with open('/proc/%s/stat' % (pid, ), 'r') as fx:
line = fx.read().split(' ')
ptime = int(line[13]) + int(line[14])
with open('/proc/stat', 'r') as fx:
linea = map(int, fx.readline().split(' ')[2:])
total_jiffies = sum(linea)
return (ptime, total_jiffies)
pid, delay, times = int(sys.argv[1]), float(sys.argv[2]), int(sys.argv[3])
try:
utime, jiffs = get_params(pid)
except IOError:
sys.stderr.write('Error: %s does not exist\n' % (pid, ))
sys.exit()
# Let's roll
for i in xrange(0, times):
time.sleep(delay)
try:
nutime, njiffs = get_params(pid)
except IOError:
sys.stderr.write('Error: %s does not exist anymore\n' % (pid, ))
sys.exit()
cpu_usage = 100 * (nutime - utime) / (njiffs - jiffs)
sys.stdout.write('%.2f\n' % (cpu_usage, ))
utime = nutime
jiffs = njiffs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment