Skip to content

Instantly share code, notes, and snippets.

@wryfi
Created October 16, 2012 23:34
Show Gist options
  • Save wryfi/3902757 to your computer and use it in GitHub Desktop.
Save wryfi/3902757 to your computer and use it in GitHub Desktop.
simple python script to check cpu utilization of lxc containers and print percentage
#!/usr/bin/python
import multiprocessing, os, re, sys, time
cgroup_dir = '/sys/fs/cgroup'
node_rgx = u'[a-z]*[0-9]{2}'
interval = 1
def main():
cpus = multiprocessing.cpu_count()
startval = get_values()
time.sleep(interval)
endval = get_values()
for key, value in startval.iteritems():
if key in endval:
delta = int(endval[key]) - int(startval[key])
dpns = float(delta / interval)
dps = dpns / 1000000000
percent = dps / cpus
print key + ':' + '{percent:.2%}'.format(percent=percent)
def get_values():
values = {}
if os.path.exists('%s/cpuacct.usage' % cgroup_dir):
with open('%s/cpuacct.usage' % cgroup_dir, 'rb') as tobj:
values['total'] = tobj.read()
else:
sys.exit(1)
for fd in os.listdir(cgroup_dir):
if os.path.isdir('%s/%s' % (cgroup_dir, fd)) and re.match(node_rgx, fd):
acctf = '%s/%s/cpuacct.usage' % (cgroup_dir, fd)
if os.path.isfile(acctf):
with open(acctf, 'rb') as accto:
values[fd] = accto.read()
return values
if __name__ == "__main__":
main()
@aziz86
Copy link

aziz86 commented Jun 26, 2015

Hi Wryfi,
Thanks a lot for your script.
I understand that it is done for all the present containers.
I have a question : does your script compute the "cpuacct.usage" for the total number of cpus or just for 1 per cpu ?
I will very appreciate your answer.
Regards.

@dresende
Copy link

dresende commented Dec 2, 2015

As you can see in line 10 (where he reaches for the total number of CPUs) and line 19 (where he divides the percentage), he is 😉

@DavidGoodwin
Copy link

Thank you!

(Forked at https://gist.github.com/palepurple/61b5f644b868ecd484c5 - add ability to suppress low usage containers and to change the interval).

@Aamir010
Copy link

Count neither match with Top nor with docker stats

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment