Skip to content

Instantly share code, notes, and snippets.

@kylegibson
Created October 26, 2010 09:50
Show Gist options
  • Save kylegibson/646617 to your computer and use it in GitHub Desktop.
Save kylegibson/646617 to your computer and use it in GitHub Desktop.
Single Process CPU Usage
#!/usr/bin/python
def get_current_cpu(pid):
d = open("/proc/%s/stat" % pid, "r").readline().split()
return int(d[13]), int(d[14])
def get_total_cpu():
d = open("/proc/stat", "r").readline()
return sum(map(int, d.split()[1:]))
def main(argv):
import time
pid = int(argv[1])
wait = int(argv[2])
cpu_before = get_current_cpu(pid)
total_before = get_total_cpu()
time.sleep(wait)
cpu_after = get_current_cpu(pid)
total_after = get_total_cpu()
total_diff = total_after - total_before
cuserp = 100 * (cpu_after[0] - cpu_before[0]) / total_diff
csysp = 100 * (cpu_after[1] - cpu_before[1]) / total_diff
print cuserp
print csysp
if __name__ == '__main__':
import sys
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment