Created
October 13, 2016 16:31
-
-
Save hashbrowncipher/96890510d25a949edf7e1d595789c3a2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import namedtuple | |
from time import sleep | |
import sys | |
import os | |
NICE_FIELD = 19 - 1 | |
DELAYACCT_BLKIO_TICKS_FIELD = 42 - 1 | |
clk_tck_factor = int(1e9 / os.sysconf('SC_CLK_TCK')) | |
STAT_FIELDS = ( | |
'blkio_delay_total', | |
) | |
SCHEDSTAT_FIELDS = ( | |
'cpu_run_virtual_total', | |
'cpu_delay_total', | |
'cpu_count', | |
) | |
ThreadStats = namedtuple('ThreadStats', STAT_FIELDS + SCHEDSTAT_FIELDS) | |
def ts_add(self, other): | |
return self.__class__(*map(sum, zip(self, other))) | |
ThreadStats.__add__ = ts_add | |
def blank_threadstats(): | |
return ThreadStats(0, 0, 0, 0) | |
def get_thread_stats(tid, stat_fields): | |
blk_delay = int(stat_fields[DELAYACCT_BLKIO_TICKS_FIELD]) | |
blk_delay *= clk_tck_factor | |
try: | |
split_schedstat = open('/proc/{}/schedstat'.format(tid)).read().split() | |
split_schedstat = map(int, split_schedstat) | |
return ThreadStats(blk_delay, *split_schedstat) | |
except IOError: | |
pass | |
def examine_thread(tid): | |
try: | |
stat_fields = open('/proc/{}/stat'.format(tid)).read().split() | |
if stat_fields[NICE_FIELD] != '0': | |
return get_thread_stats(tid, stat_fields) | |
except IOError: | |
pass | |
def get_all_thread_stats(pid): | |
threads = os.listdir('/proc/{}/task'.format(pid)) | |
for tid in threads: | |
info = examine_thread(tid) | |
if info is not None: | |
yield tid, info | |
def main(): | |
pid = sys.argv[1] | |
exited_count = 0 | |
exited = blank_threadstats() | |
old_threads = dict() | |
while True: | |
new_threads = dict(get_all_thread_stats(pid)) | |
for tid in new_threads: | |
old_threads.pop(tid, None) | |
exited = sum(old_threads.values(), exited) | |
exited_count += len(old_threads) | |
print exited_count, sum(new_threads.values(), exited) | |
old_threads = new_threads | |
sleep(1) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment