Archive for June, 2007

Python: Find out cpu time of a certain process

To find out how many percentage a certain process uses the cpu:

PYTHON:
  1. import os, time
  2.  
  3. # find out the pid by username.
  4. # "-o pid h" omits the header and just prints the pid
  5. pid = os.popen('ps -U my_user_name -o pid h').read().strip()
  6.  
  7. # 14th column is utime, 15th column is stime:
  8. # The time the process has been scheduled in user/kernel mode
  9. # The time value is in jiffies. One jiffie is appox 1/100 second
  10. # see man proc for more info
  11. stat = os.popen('cat /proc/%s/stat' % pid).read().strip()
  12. cpu_time1=int(stat.split()[14]) + int(stat.split()[15])
  13. time1=time.time()
  14.  
  15. time.sleep(1)
  16. stat = os.popen('cat /proc/%s/stat' % pid).read().strip()
  17. cpu_time2=int(stat.split()[14]) + int(stat.split()[15])
  18. time2=time.time()
  19.  
  20. print str(float(cpu_time2 - cpu_time1) / (time2 - time1)) + "%"

I don't know though if the number is accurate.
What is "cpu time" anyway? It's the time the process is running (using the cpu for 100%) divided by the time the process is laid asleep by the scheduler.
Then, jiffies seem to be not a safe number for time measurements.
But for relative measurements it should do the trick.