Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get load at a moment in time or getloadavg() for a smaller time period in Python in Linux (CentOS)

Tags:

python

linux

load

Currently, am using Python's os.getloadavg() to get an idea of the current load on the server (Centos 6.3)

According to the python documentation, os.getloadavg() "Returns the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes" :

http://docs.python.org/2/library/os.html#os.getloadavg

os.getloadavg()
Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes or raises OSError if the load average was unobtainable.

Question:

  • Is it possible to get the number of processes in the system run queue at the current instant?
  • If not, is it possible to get the average over a shorter period of time, like the last 5 or 10 seconds?

The reason I am asking is because I am getting the load average, then if it is too high, am killing some processes. This can potentially happen many times per minute, so am concerned too many processes will be killed before the 1 minute average catches up.

Thanks!

like image 513
Chris Dutrow Avatar asked Oct 05 '22 21:10

Chris Dutrow


1 Answers

According to Documentation/filesystems/proc.txt in the Linux 3.5 kernel source, you can retrieve the number of currently running processes from /proc/stat:

>>> for l in open("/proc/stat"):
...   l = l.split()
...   if l[0] == 'procs_running':
...     result = int(l[1])
... 
>>> print result
6
>>> 

The same number is available in /proc/loadavg:

>>> print int(open("/proc/loadavg").next().split()[3].split('/')[0])
6
like image 120
Robᵩ Avatar answered Oct 13 '22 12:10

Robᵩ