#!/usr/bin/python

from bcc import BPF
from time import sleep
from ctypes import c_ushort, c_int, c_ulonglong
from sys import argv

def usage():
	print("[interval] [count]")
	exit(0)

print("Hit Ctrl-C to end.")
count = 100
interval = 5
loop = 0
# load BPF program
b = BPF(src_file="dbus-top.c")

b.attach_uprobe(name="dbus-1", sym="_dbus_poll", fn_name="do_entry")

b.attach_uretprobe(name="dbus-1", sym="_dbus_poll", fn_name="do_return")

while (1):
	if count > 0:

		loop += 1
		if loop > count:
			exit()
	sleep(interval)
	print ("%d : \n" % loop)
	stats_t = b["stats"]
	timestamp = b["timestamp_e"]
	timeframe = 0
	for v in timestamp.values():
		timeframe = v.value
	timestamp = b["timestamp_b"]
	for v in timestamp.values():
		timeframe -= v.value
	for v in stats_t.values():
		v.usage = (v.run * 100 / timeframe)
	for v in sorted(stats_t.values(), key=lambda stats_t: stats_t.run, reverse=True):
		print("%10d %20s %10.6f" % (v.pid, v.buf.encode('string-escape'), float(v.run) / float(timeframe)))
