def _open_trace(self):
traces = TraceCollection()
- handle = traces.add_traces_recursive(self._arg_path, "ctf")
+ handle = traces.add_traces_recursive(self._arg_path, 'ctf')
if handle == {}:
- self._gen_error("Failed to open " + self._arg_path, -1)
+ self._gen_error('Failed to open ' + self._arg_path, -1)
self._handle = handle
self._traces = traces
common.process_date_args(self)
self._traces.remove_trace(h)
def _check_lost_events(self):
- print("Checking the trace for lost events...")
+ print('Checking the trace for lost events...')
try:
- subprocess.check_output("babeltrace %s" % self._arg_path,
+ subprocess.check_output('babeltrace %s' % self._arg_path,
shell=True)
except subprocess.CalledProcessError:
- print("Error running babeltrace on the trace, cannot verify if "
- "events were lost during the trace recording")
+ print('Error running babeltrace on the trace, cannot verify if '
+ 'events were lost during the trace recording')
def _run_analysis(self, reset_cb, refresh_cb, break_cb=None):
self.trace_start_ts = 0
if self._enable_proc_filter_args:
self._arg_proc_list = None
if args.procname:
- self._arg_proc_list = args.procname.split(",")
+ self._arg_proc_list = args.procname.split(',')
self._arg_pid_list = None
if args.pid:
- self._arg_pid_list = args.pid.split(",")
+ self._arg_pid_list = args.pid.split(',')
if self._enable_max_min_arg:
self._arg_max = args.max
ap = argparse.ArgumentParser(description=self._DESC)
# common arguments
- ap.add_argument('path', metavar="<path/to/trace>", help='trace path')
+ ap.add_argument('path', metavar='<path/to/trace>', help='trace path')
ap.add_argument('-r', '--refresh', type=int,
help='Refresh period in seconds')
ap.add_argument('--limit', type=int, default=10,
help='Limit to top X (default = 10)')
- ap.add_argument('--no-progress', action="store_true",
+ ap.add_argument('--no-progress', action='store_true',
help='Don\'t display the progress bar')
- ap.add_argument('--skip-validation', action="store_true",
+ ap.add_argument('--skip-validation', action='store_true',
help='Skip the trace validation')
- ap.add_argument('--gmt', action="store_true",
+ ap.add_argument('--gmt', action='store_true',
help='Manipulate timestamps based on GMT instead '
'of local time')
ap.add_argument('--begin', type=str, help='start time: '
'less that minsize bytes')
if self._enable_freq_arg:
- ap.add_argument('--freq', action="store_true",
+ ap.add_argument('--freq', action='store_true',
help='Show the frequency distribution of '
'handler duration')
ap.add_argument('--freq-resolution', type=int, default=20,
'(default 20)')
if self._enable_log_arg:
- ap.add_argument('--log', action="store_true",
+ ap.add_argument('--log', action='store_true',
help='Display the events in the order they '
'appeared')
if self._enable_stats_arg:
- ap.add_argument('--stats', action="store_true",
+ ap.add_argument('--stats', action='store_true',
help='Display the statistics')
# specific arguments
continue
if tid.tid == 0:
continue
- pc = float("%0.02f" % ((tid.cpu_ns * 100) / total_ns))
+ pc = float('%0.02f' % ((tid.cpu_ns * 100) / total_ns))
if tid.migrate_count > 0:
- migrations = ", %d migrations" % (tid.migrate_count)
+ migrations = ', %d migrations' % (tid.migrate_count)
else:
- migrations = ""
- values.append(("%s (%d)%s" % (tid.comm, tid.tid, migrations), pc))
+ migrations = ''
+ values.append(('%s (%d)%s' % (tid.comm, tid.tid, migrations), pc))
count = count + 1
if limit > 0 and count >= limit:
break
- for line in graph.graph("Per-TID CPU Usage", values, unit=" %"):
+ for line in graph.graph('Per-TID CPU Usage', values, unit=' %'):
print(line)
values = []
total_cpu_pc = 0
for cpu in sorted(self.state.cpus.values(),
key=operator.attrgetter('cpu_ns'), reverse=True):
- cpu_pc = float("%0.02f" % cpu.cpu_pc)
+ cpu_pc = float('%0.02f' % cpu.cpu_pc)
total_cpu_pc += cpu_pc
- values.append(("CPU %d" % cpu.cpu_id, cpu_pc))
- for line in graph.graph("Per-CPU Usage", values, unit=" %"):
+ values.append(('CPU %d' % cpu.cpu_id, cpu_pc))
+ for line in graph.graph('Per-CPU Usage', values, unit=' %'):
print(line)
- print("\nTotal CPU Usage: %0.02f%%\n" %
+ print('\nTotal CPU Usage: %0.02f%%\n' %
(total_cpu_pc / len(self.state.cpus.keys())))
def _add_arguments(self, ap):
def add_fd_dict(self, tid, fd, files):
if fd.read == 0 and fd.write == 0:
return
- if fd.filename.startswith("pipe") or \
- fd.filename.startswith("socket") or \
- fd.filename.startswith("anon_inode") or \
- fd.filename.startswith("unknown"):
- filename = "%s (%s)" % (fd.filename, tid.comm)
+ if fd.filename.startswith('pipe') or \
+ fd.filename.startswith('socket') or \
+ fd.filename.startswith('anon_inode') or \
+ fd.filename.startswith('unknown'):
+ filename = '%s (%s)' % (fd.filename, tid.comm)
files[filename] = {}
- files[filename]["read"] = fd.read
- files[filename]["write"] = fd.write
- files[filename]["name"] = filename
- files[filename]["other"] = ["fd %d in %s (%d)" % (fd.fd,
+ files[filename]['read'] = fd.read
+ files[filename]['write'] = fd.write
+ files[filename]['name'] = filename
+ files[filename]['other'] = ['fd %d in %s (%d)' % (fd.fd,
tid.comm, tid.pid)]
else:
# merge counters of shared files
filename = fd.filename
if filename not in files.keys():
files[filename] = {}
- files[filename]["read"] = fd.read
- files[filename]["write"] = fd.write
- files[filename]["name"] = filename
- files[filename]["other"] = ["fd %d in %s (%d)" %
+ files[filename]['read'] = fd.read
+ files[filename]['write'] = fd.write
+ files[filename]['name'] = filename
+ files[filename]['other'] = ['fd %d in %s (%d)' %
(fd.fd, tid.comm, tid.pid)]
- files[filename]["tids"] = [tid.tid]
+ files[filename]['tids'] = [tid.tid]
else:
- files[filename]["read"] += fd.read
- files[filename]["write"] += fd.write
- files[filename]["other"].append("fd %d in %s (%d)" %
+ files[filename]['read'] += fd.read
+ files[filename]['write'] += fd.write
+ files[filename]['other'].append('fd %d in %s (%d)' %
(fd.fd, tid.comm,
tid.pid))
sorted_f = sorted(files.items(), key=lambda files: files[1]['read'],
reverse=True)
for f in sorted_f:
- if f[1]["read"] == 0:
+ if f[1]['read'] == 0:
continue
- info_fmt = "{:>10}".format(common.convert_size(f[1]["read"],
+ info_fmt = '{:>10}'.format(common.convert_size(f[1]['read'],
padding_after=True))
- values.append(("%s %s %s" % (info_fmt,
- f[1]["name"],
- str(f[1]["other"])[1:-1]),
- f[1]["read"]))
+ values.append(('%s %s %s' % (info_fmt,
+ f[1]['name'],
+ str(f[1]['other'])[1:-1]),
+ f[1]['read']))
count = count + 1
if limit > 0 and count >= limit:
break
sorted_f = sorted(files.items(), key=lambda files: files[1]['write'],
reverse=True)
for f in sorted_f:
- if f[1]["write"] == 0:
+ if f[1]['write'] == 0:
continue
- info_fmt = "{:>10}".format(common.convert_size(f[1]["write"],
+ info_fmt = '{:>10}'.format(common.convert_size(f[1]['write'],
padding_after=True))
- values.append(("%s %s %s" % (info_fmt,
- f[1]["name"],
- str(f[1]["other"])[1:-1]),
- f[1]["write"]))
+ values.append(('%s %s %s' % (info_fmt,
+ f[1]['name'],
+ str(f[1]['other'])[1:-1]),
+ f[1]['write']))
count = count + 1
if limit > 0 and count >= limit:
break
key=operator.attrgetter('read'), reverse=True):
if not self.filter_process(tid):
continue
- info_fmt = "{:>10} {:<25} {:>9} file {:>9} net {:>9} unknown"
+ info_fmt = '{:>10} {:<25} {:>9} file {:>9} net {:>9} unknown'
values.append((info_fmt.format(
common.convert_size(tid.read, padding_after=True),
- "%s (%d)" % (tid.comm, tid.pid),
+ '%s (%d)' % (tid.comm, tid.pid),
common.convert_size(tid.disk_read,
padding_after=True),
common.convert_size(tid.net_read,
key=operator.attrgetter('write'), reverse=True):
if not self.filter_process(tid):
continue
- info_fmt = "{:>10} {:<25} {:>9} file {:>9} net {:>9} unknown "
+ info_fmt = '{:>10} {:<25} {:>9} file {:>9} net {:>9} unknown '
values.append((info_fmt.format(
common.convert_size(tid.write, padding_after=True),
- "%s (%d)" % (tid.comm, tid.pid),
+ '%s (%d)' % (tid.comm, tid.pid),
common.convert_size(tid.disk_write,
padding_after=True),
common.convert_size(tid.net_write,
if tid.block_read == 0:
continue
- info_fmt = "{:>10} {:<22}"
+ info_fmt = '{:>10} {:<22}'
comm = tid.comm
if not comm:
- comm = "unknown"
+ comm = 'unknown'
pid = tid.pid
if not pid:
- pid = "unknown"
+ pid = 'unknown'
else:
pid = str(pid)
values.append((info_fmt.format(
common.convert_size(tid.block_read, padding_after=True),
- "%s (pid=%s)" % (comm, pid)),
+ '%s (pid=%s)' % (comm, pid)),
tid.block_read))
count = count + 1
if tid.block_write == 0:
continue
- info_fmt = "{:>10} {:<22}"
+ info_fmt = '{:>10} {:<22}'
comm = tid.comm
if not comm:
- comm = "unknown"
+ comm = 'unknown'
pid = tid.pid
if not pid:
- pid = "unknown"
+ pid = 'unknown'
else:
pid = str(pid)
values.append((info_fmt.format(
common.convert_size(tid.block_write, padding_after=True),
- "%s (pid=%s)" % (comm, pid)),
+ '%s (pid=%s)' % (comm, pid)),
tid.block_write))
count = count + 1
if disk.nr_sector == 0:
continue
values.append((disk.prettyname, disk.nr_sector))
- for line in graph.graph('Disk nr_sector', values, unit=" sectors"):
+ for line in graph.graph('Disk nr_sector', values, unit=' sectors'):
print(line)
def iotop_output_nr_requests(self):
if disk.nr_sector == 0:
continue
values.append((disk.prettyname, disk.nr_requests))
- for line in graph.graph('Disk nr_requests', values, unit=" requests"):
+ for line in graph.graph('Disk nr_requests', values, unit=' requests'):
print(line)
def iotop_output_dev_latency(self):
continue
total = (disk.request_time / disk.completed_requests) \
/ common.MSEC_PER_NSEC
- total = float("%0.03f" % total)
- values.append(("%s" % disk.prettyname, total))
+ total = float('%0.03f' % total)
+ values.append(('%s' % disk.prettyname, total))
for line in graph.graph('Disk request time/sector', values, sort=2,
- unit=" ms"):
+ unit=' ms'):
print(line)
def iotop_output_net_recv_bytes(self):
for iface in sorted(self.state.ifaces.values(),
key=operator.attrgetter('recv_bytes'),
reverse=True):
- values.append(("%s %s" % (common.convert_size(iface.recv_bytes),
+ values.append(('%s %s' % (common.convert_size(iface.recv_bytes),
iface.name),
iface.recv_bytes))
for line in graph.graph('Network recv_bytes', values,
for iface in sorted(self.state.ifaces.values(),
key=operator.attrgetter('send_bytes'),
reverse=True):
- values.append(("%s %s" % (common.convert_size(iface.send_bytes),
+ values.append(('%s %s' % (common.convert_size(iface.send_bytes),
iface.name),
iface.send_bytes))
for line in graph.graph('Network sent_bytes', values,
g = []
i = 0
for v in values:
- g.append(("%0.03f" % (i * step + _min), v))
+ g.append(('%0.03f' % (i * step + _min), v))
i += 1
for line in graph.graph(title, g, info_before=True, count=True):
print(line)
- print("")
+ print('')
def compute_disk_stats(self, dev):
_max = 0
if count > 2:
stdev = statistics.stdev(values) / 1000
else:
- stdev = "?"
+ stdev = '?'
dev.min = _min / 1000
dev.max = _max / 1000
dev.total = total / 1000
self.iolatency_freq_histogram(d.min, d.max,
self._arg_freq_resolution,
d.rq_values,
- "Frequency distribution for "
- "disk %s (usec)" %
+ 'Frequency distribution for '
+ 'disk %s (usec)' %
(d.prettyname))
def iolatency_output(self):
# for proc in self.latency_hist.keys():
# values = []
# for v in self.latency_hist[proc]:
-# values.append(("%s" % (v[0]), v[1]))
+# values.append(('%s' % (v[0]), v[1]))
# for line in graph.graph('%s requests latency (ms)' % proc, values,
-# unit=" ms"):
+# unit=' ms'):
# print(line)
def iostats_minmax(self, duration, current_min, current_max):
def iostats_syscalls_line(self, fmt, name, count, _min, _max, total, rq):
if count < 2:
- stdev = "?"
+ stdev = '?'
else:
- stdev = "%0.03f" % (statistics.stdev(rq) / 1000)
+ stdev = '%0.03f' % (statistics.stdev(rq) / 1000)
if count < 1:
- avg = "0.000"
+ avg = '0.000'
else:
- avg = "%0.03f" % (total / (count * 1000))
+ avg = '%0.03f' % (total / (count * 1000))
if _min is None:
_min = 0
- _min = "%0.03f" % (_min / 1000)
- _max = "%0.03f" % (_max / 1000)
+ _min = '%0.03f' % (_min / 1000)
+ _max = '%0.03f' % (_max / 1000)
print(fmt.format(name, count, _min, avg, _max, stdev))
def account_syscall_iorequests(self, s, iorequests):
def iostats_output_syscalls(self):
s = self.syscalls_stats
- print("\nSyscalls latency statistics (usec):")
- fmt = "{:<14} {:>14} {:>14} {:>14} {:>14} {:>14}"
- print(fmt.format("Type", "Count", "Min", "Average",
- "Max", "Stdev"))
- print("-" * 89)
- self.iostats_syscalls_line(fmt, "Open", s.open_count, s.open_min,
+ print('\nSyscalls latency statistics (usec):')
+ fmt = '{:<14} {:>14} {:>14} {:>14} {:>14} {:>14}'
+ print(fmt.format('Type', 'Count', 'Min', 'Average',
+ 'Max', 'Stdev'))
+ print('-' * 89)
+ self.iostats_syscalls_line(fmt, 'Open', s.open_count, s.open_min,
s.open_max, s.open_total, s.open_rq)
- self.iostats_syscalls_line(fmt, "Read", s.read_count, s.read_min,
+ self.iostats_syscalls_line(fmt, 'Read', s.read_count, s.read_min,
s.read_max, s.read_total, s.read_rq)
- self.iostats_syscalls_line(fmt, "Write", s.write_count, s.write_min,
+ self.iostats_syscalls_line(fmt, 'Write', s.write_count, s.write_min,
s.write_max, s.write_total, s.write_rq)
- self.iostats_syscalls_line(fmt, "Sync", s.sync_count, s.sync_min,
+ self.iostats_syscalls_line(fmt, 'Sync', s.sync_count, s.sync_min,
s.sync_max, s.sync_total, s.sync_rq)
def iolatency_syscalls_output(self):
s = self.syscalls_stats
- print("")
+ print('')
if s.open_count > 0:
self.iolatency_freq_histogram(s.open_min/1000, s.open_max/1000,
self._arg_freq_resolution, s.open_rq,
- "Open latency distribution (usec)")
+ 'Open latency distribution (usec)')
if s.read_count > 0:
self.iolatency_freq_histogram(s.read_min/1000, s.read_max/1000,
self._arg_freq_resolution, s.read_rq,
- "Read latency distribution (usec)")
+ 'Read latency distribution (usec)')
if s.write_count > 0:
self.iolatency_freq_histogram(s.write_min/1000, s.write_max/1000,
self._arg_freq_resolution,
s.write_rq,
- "Write latency distribution (usec)")
+ 'Write latency distribution (usec)')
if s.sync_count > 0:
self.iolatency_freq_histogram(s.sync_min/1000, s.sync_max/1000,
self._arg_freq_resolution, s.sync_rq,
- "Sync latency distribution (usec)")
+ 'Sync latency distribution (usec)')
def iolatency_syscalls_list_output(self, title, rq_list,
sortkey, reverse):
return
print(title)
if self._arg_extra:
- extra_fmt = "{:<48}"
- extra_title = "{:<8} {:<8} {:<8} {:<8} {:<8} {:<8} ".format(
- "Dirtied", "Alloc", "Free", "Written", "Kswap", "Cleared")
+ extra_fmt = '{:<48}'
+ extra_title = '{:<8} {:<8} {:<8} {:<8} {:<8} {:<8} '.format(
+ 'Dirtied', 'Alloc', 'Free', 'Written', 'Kswap', 'Cleared')
else:
- extra_fmt = "{:<0}"
- extra_title = ""
- title_fmt = "{:<19} {:<20} {:<16} {:<23} {:<5} {:<24} {:<8} " + \
- extra_fmt + "{:<14}"
- fmt = "{:<40} {:<16} {:>16} {:>11} {:<24} {:<8} " + \
- extra_fmt + "{:<14}"
- print(title_fmt.format("Begin", "End", "Name", "Duration (usec)",
- "Size", "Proc", "PID", extra_title, "Filename"))
+ extra_fmt = '{:<0}'
+ extra_title = ''
+ title_fmt = '{:<19} {:<20} {:<16} {:<23} {:<5} {:<24} {:<8} ' + \
+ extra_fmt + '{:<14}'
+ fmt = '{:<40} {:<16} {:>16} {:>11} {:<24} {:<8} ' + \
+ extra_fmt + '{:<14}'
+ print(title_fmt.format('Begin', 'End', 'Name', 'Duration (usec)',
+ 'Size', 'Proc', 'PID', extra_title, 'Filename'))
for rq in sorted(rq_list,
key=operator.attrgetter(sortkey), reverse=reverse):
- # only limit the output if in the "top" view
+ # only limit the output if in the 'top' view
if reverse and count > limit:
break
if rq.size is None:
- size = "N/A"
+ size = 'N/A'
else:
size = common.convert_size(rq.size)
if self._arg_extra:
- extra = "{:<8} {:<8} {:<8} {:<8} {:<8} {:<8} ".format(
+ extra = '{:<8} {:<8} {:<8} {:<8} {:<8} {:<8} '.format(
rq.dirty, rq.page_alloc, rq.page_free, rq.page_written,
rq.woke_kswapd, rq.page_cleared)
else:
- extra = ""
- name = rq.name.replace("syscall_entry_", "").replace("sys_", "")
+ extra = ''
+ name = rq.name.replace('syscall_entry_', '').replace('sys_', '')
if rq.fd is None:
- filename = "None"
- fd = "None"
+ filename = 'None'
+ fd = 'None'
else:
filename = rq.fd.filename
fd = rq.fd.fd
end = common.ns_to_hour_nsec(rq.end, self._arg_multi_day,
self._arg_gmt)
- outrange = " "
+ outrange = ' '
duration = rq.duration
if self._arg_begin and rq.begin < self._arg_begin:
- outrange = "*"
+ outrange = '*'
outrange_legend = True
if self._arg_end and rq.end > self._arg_end:
- outrange = "*"
+ outrange = '*'
outrange_legend = True
- print(fmt.format("[" + common.ns_to_hour_nsec(
- rq.begin, self._arg_multi_day, self._arg_gmt) + "," +
- end + "]" + outrange,
+ print(fmt.format('[' + common.ns_to_hour_nsec(
+ rq.begin, self._arg_multi_day, self._arg_gmt) + ',' +
+ end + ']' + outrange,
name,
- "%0.03f" % (duration/1000) + outrange,
+ '%0.03f' % (duration/1000) + outrange,
size, rq.proc.comm,
rq.proc.pid, extra,
- "%s (fd=%s)" % (filename, fd)))
+ '%s (fd=%s)' % (filename, fd)))
count += 1
if outrange_legend:
- print("*: Syscalls started and/or completed outside of the "
- "range specified")
+ print('*: Syscalls started and/or completed outside of the '
+ 'range specified')
def iolatency_syscalls_top_output(self):
s = self.syscalls_stats
self.iolatency_syscalls_list_output(
- "\nTop open syscall latencies (usec)", s.all_open,
- "duration", True)
+ '\nTop open syscall latencies (usec)', s.all_open,
+ 'duration', True)
self.iolatency_syscalls_list_output(
- "\nTop read syscall latencies (usec)", s.all_read,
- "duration", True)
+ '\nTop read syscall latencies (usec)', s.all_read,
+ 'duration', True)
self.iolatency_syscalls_list_output(
- "\nTop write syscall latencies (usec)", s.all_write,
- "duration", True)
+ '\nTop write syscall latencies (usec)', s.all_write,
+ 'duration', True)
self.iolatency_syscalls_list_output(
- "\nTop sync syscall latencies (usec)", s.all_sync,
- "duration", True)
+ '\nTop sync syscall latencies (usec)', s.all_sync,
+ 'duration', True)
def iolatency_syscalls_log_output(self):
s = self.syscalls_stats
self.iolatency_syscalls_list_output(
- "\nLog of all I/O system calls",
+ '\nLog of all I/O system calls',
s.all_open + s.all_read + s.all_write + s.all_sync,
- "begin", False)
+ 'begin', False)
# iostats functions
def iostats_output_disk(self):
# TODO same with network
if not self.state.disks:
return
- print("\nDisk latency statistics (usec):")
- fmt = "{:<14} {:>14} {:>14} {:>14} {:>14} {:>14}"
- print(fmt.format("Name", "Count", "Min", "Average", "Max", "Stdev"))
- print("-" * 89)
+ print('\nDisk latency statistics (usec):')
+ fmt = '{:<14} {:>14} {:>14} {:>14} {:>14} {:>14}'
+ print(fmt.format('Name', 'Count', 'Min', 'Average', 'Max', 'Stdev'))
+ print('-' * 89)
for dev in self.state.disks.keys():
d = self.state.disks[dev]
tid.init_counts()
def _add_arguments(self, ap):
- ap.add_argument('--usage', action="store_true",
+ ap.add_argument('--usage', action='store_true',
help='Show the I/O usage')
- ap.add_argument('--latencystats', action="store_true",
+ ap.add_argument('--latencystats', action='store_true',
help='Show the I/O latency statistics')
- ap.add_argument('--latencytop', action="store_true",
+ ap.add_argument('--latencytop', action='store_true',
help='Show the I/O latency top')
- ap.add_argument('--latencyfreq', action="store_true",
+ ap.add_argument('--latencyfreq', action='store_true',
help='Show the I/O latency frequency distribution')
ap.add_argument('--freq-resolution', type=int, default=20,
help='Frequency distribution resolution '
self._arg_irq_filter_list = None
self._arg_softirq_filter_list = None
if self._args.irq:
- self._arg_irq_filter_list = self._args.irq.split(",")
+ self._arg_irq_filter_list = self._args.irq.split(',')
if self._args.softirq:
- self._arg_softirq_filter_list = self._args.softirq.split(",")
+ self._arg_softirq_filter_list = self._args.softirq.split(',')
if self._arg_irq_filter_list is None and \
self._arg_softirq_filter_list is None:
self._arg_irq_filter_list = []
values = []
raise_delays = []
stdev = {}
- for j in irq["list"]:
+ for j in irq['list']:
delay = j.stop_ts - j.start_ts
values.append(delay)
if j.raise_ts is None:
# Raise latency (only for some softirqs)
r_d = j.start_ts - j.raise_ts
raise_delays.append(r_d)
- if irq["count"] < 2:
- stdev["duration"] = "?"
+ if irq['count'] < 2:
+ stdev['duration'] = '?'
else:
- stdev["duration"] = "%0.03f" % (statistics.stdev(values) / 1000)
+ stdev['duration'] = '%0.03f' % (statistics.stdev(values) / 1000)
# format string for the raise if present
- if irq["raise_count"] >= 2:
- stdev["raise"] = "%0.03f" % (statistics.stdev(raise_delays)/1000)
+ if irq['raise_count'] >= 2:
+ stdev['raise'] = '%0.03f' % (statistics.stdev(raise_delays)/1000)
return stdev
def irq_list_to_freq(self, irq, _min, _max, res, name, nr):
for i in range(res):
buckets.append(i * step)
values.append(0)
- for i in irq["list"]:
+ for i in irq['list']:
v = (i.stop_ts - i.start_ts) / 1000
b = min(int((v-_min)/step), res - 1)
values[b] += 1
g = []
i = 0
for v in values:
- g.append(("%0.03f" % (i * step + _min), v))
+ g.append(('%0.03f' % (i * step + _min), v))
i += 1
for line in graph.graph('Handler duration frequency distribution %s '
'(%s) (usec)' % (name, nr),
g, info_before=True, count=True):
print(line)
- print("")
+ print('')
# FIXME: there must be a way to make that more complicated/ugly
def filter_irq(self, i):
if self._arg_irq_filter_list is not None and \
len(self._arg_irq_filter_list) > 0:
return False
- raise Exception("WTF")
+ raise Exception('WTF')
def log_irq(self):
- fmt = "[{:<18}, {:<18}] {:>15} {:>4} {:<9} {:>4} {:<22}"
- title_fmt = "{:<20} {:<19} {:>15} {:>4} {:<9} {:>4} {:<22}"
- print(title_fmt.format("Begin", "End", "Duration (us)", "CPU",
- "Type", "#", "Name"))
- for i in self.state.interrupts["irq-list"]:
+ fmt = '[{:<18}, {:<18}] {:>15} {:>4} {:<9} {:>4} {:<22}'
+ title_fmt = '{:<20} {:<19} {:>15} {:>4} {:<9} {:>4} {:<22}'
+ print(title_fmt.format('Begin', 'End', 'Duration (us)', 'CPU',
+ 'Type', '#', 'Name'))
+ for i in self.state.interrupts['irq-list']:
if not self.filter_irq(i):
continue
if i.irqclass == sv.IRQ.HARD_IRQ:
- name = self.state.interrupts["names"][i.nr]
- irqtype = "IRQ"
+ name = self.state.interrupts['names'][i.nr]
+ irqtype = 'IRQ'
else:
name = sv.IRQ.soft_names[i.nr]
- irqtype = "SoftIRQ"
+ irqtype = 'SoftIRQ'
if i.raise_ts is not None:
- raise_ts = " (raised at %s)" % \
+ raise_ts = ' (raised at %s)' % \
(common.ns_to_hour_nsec(i.raise_ts,
self._arg_multi_day,
self._arg_gmt))
else:
- raise_ts = ""
+ raise_ts = ''
print(fmt.format(common.ns_to_hour_nsec(i.start_ts,
self._arg_multi_day,
self._arg_gmt),
common.ns_to_hour_nsec(i.stop_ts,
self._arg_multi_day,
self._arg_gmt),
- "%0.03f" % ((i.stop_ts - i.start_ts) / 1000),
- "%d" % i.cpu_id, irqtype, i.nr, name + raise_ts))
+ '%0.03f' % ((i.stop_ts - i.start_ts) / 1000),
+ '%d' % i.cpu_id, irqtype, i.nr, name + raise_ts))
def print_irq_stats(self, dic, name_table, filter_list, header):
header_output = 0
stdev = self.compute_stdev(dic[i])
# format string for the raise if present
- if dic[i]["raise_count"] < 2:
- raise_stats = " |"
+ if dic[i]['raise_count'] < 2:
+ raise_stats = ' |'
else:
- r_avg = dic[i]["raise_total"] / (dic[i]["raise_count"] * 1000)
- raise_stats = " | {:>6} {:>12} {:>12} {:>12} {:>12}".format(
- dic[i]["raise_count"],
- "%0.03f" % (dic[i]["raise_min"] / 1000),
- "%0.03f" % r_avg,
- "%0.03f" % (dic[i]["raise_max"] / 1000),
- stdev["raise"])
+ r_avg = dic[i]['raise_total'] / (dic[i]['raise_count'] * 1000)
+ raise_stats = ' | {:>6} {:>12} {:>12} {:>12} {:>12}'.format(
+ dic[i]['raise_count'],
+ '%0.03f' % (dic[i]['raise_min'] / 1000),
+ '%0.03f' % r_avg,
+ '%0.03f' % (dic[i]['raise_max'] / 1000),
+ stdev['raise'])
# final output
- if dic[i]["count"] == 0:
+ if dic[i]['count'] == 0:
continue
- avg = "%0.03f" % (dic[i]["total"] / (dic[i]["count"] * 1000))
+ avg = '%0.03f' % (dic[i]['total'] / (dic[i]['count'] * 1000))
format_str = '{:<3} {:<18} {:>5} {:>12} {:>12} {:>12} ' \
'{:>12} {:<60}'
- s = format_str.format("%d:" % i, "<%s>" % name, dic[i]["count"],
- "%0.03f" % (dic[i]["min"] / 1000),
- "%s" % (avg),
- "%0.03f" % (dic[i]["max"] / 1000),
- "%s" % (stdev["duration"]),
+ s = format_str.format('%d:' % i, '<%s>' % name, dic[i]['count'],
+ '%0.03f' % (dic[i]['min'] / 1000),
+ '%s' % (avg),
+ '%0.03f' % (dic[i]['max'] / 1000),
+ '%s' % (stdev['duration']),
raise_stats)
if self._arg_stats and (self._arg_freq or header_output == 0):
print(header)
if self._arg_stats:
print(s)
if self._arg_freq:
- self.irq_list_to_freq(dic[i], dic[i]["min"] / 1000,
- dic[i]["max"] / 1000,
+ self.irq_list_to_freq(dic[i], dic[i]['min'] / 1000,
+ dic[i]['max'] / 1000,
self._arg_freq_resolution, name, str(i))
def _print_results(self, begin_ns, end_ns):
print(date)
if self._arg_irq_filter_list is not None:
- header = ""
- header += '{:<52} {:<12}\n'.format("Hard IRQ", "Duration (us)")
+ header = ''
+ header += '{:<52} {:<12}\n'.format('Hard IRQ', 'Duration (us)')
header += '{:<22} {:<14} {:<12} {:<12} {:<10} ' \
- '{:<12}\n'.format("", "count", "min", "avg", "max",
- "stdev")
- header += ('-'*82 + "|")
- self.print_irq_stats(self.state.interrupts["hard-irqs"],
- self.state.interrupts["names"],
+ '{:<12}\n'.format('', 'count', 'min', 'avg', 'max',
+ 'stdev')
+ header += ('-'*82 + '|')
+ self.print_irq_stats(self.state.interrupts['hard-irqs'],
+ self.state.interrupts['names'],
self._arg_irq_filter_list, header)
- print("")
+ print('')
if self._arg_softirq_filter_list is not None:
- header = ""
- header += '{:<52} {:<52} {:<12}\n'.format("Soft IRQ",
- "Duration (us)",
- "Raise latency (us)")
+ header = ''
+ header += '{:<52} {:<52} {:<12}\n'.format('Soft IRQ',
+ 'Duration (us)',
+ 'Raise latency (us)')
header += '{:<22} {:<14} {:<12} {:<12} {:<10} {:<4} {:<3} {:<14} '\
'{:<12} {:<12} {:<10} ' \
- '{:<12}\n'.format("", "count", "min", "avg", "max",
- "stdev", " |", "count", "min",
- "avg", "max", "stdev")
- header += '-' * 82 + "|" + '-' * 60
- self.print_irq_stats(self.state.interrupts["soft-irqs"],
+ '{:<12}\n'.format('', 'count', 'min', 'avg', 'max',
+ 'stdev', ' |', 'count', 'min',
+ 'avg', 'max', 'stdev')
+ header += '-' * 82 + '|' + '-' * 60
+ self.print_irq_stats(self.state.interrupts['soft-irqs'],
sv.IRQ.soft_names,
self._arg_softirq_filter_list,
header)
- print("")
+ print('')
def _compute_stats(self):
pass
def _reset_total(self, start_ts):
- self.state.interrupts["hard_count"] = 0
- self.state.interrupts["soft_count"] = 0
- self.state.interrupts["irq-list"] = []
- for i in self.state.interrupts["hard-irqs"].keys():
- self.state.interrupts["hard-irqs"][i] = sv.IRQ.init_irq_instance()
- for i in self.state.interrupts["soft-irqs"].keys():
- self.state.interrupts["soft-irqs"][i] = sv.IRQ.init_irq_instance()
+ self.state.interrupts['hard_count'] = 0
+ self.state.interrupts['soft_count'] = 0
+ self.state.interrupts['irq-list'] = []
+ for i in self.state.interrupts['hard-irqs'].keys():
+ self.state.interrupts['hard-irqs'][i] = sv.IRQ.init_irq_instance()
+ for i in self.state.interrupts['soft-irqs'].keys():
+ self.state.interrupts['soft-irqs'][i] = sv.IRQ.init_irq_instance()
def _refresh(self, begin, end):
self._compute_stats()
self.state.tids[tid].freed_pages = 0
def _refresh(self, begin, end):
- print("hey")
+ print('hey')
self._compute_stats()
self._print_results(begin, end)
self._reset_total(end)
if not self.filter_process(tid):
continue
- values.append(("%s (%d)" % (tid.comm, tid.tid),
+ values.append(('%s (%d)' % (tid.comm, tid.tid),
tid.allocated_pages))
count += 1
if self._arg_limit > 0 and count >= self._arg_limit:
break
- for line in graph.graph("Per-TID Memory Allocations", values,
- unit=" pages"):
+ for line in graph.graph('Per-TID Memory Allocations', values,
+ unit=' pages'):
print(line)
def _print_per_tid_freed(self):
if not self.filter_process(tid):
continue
- values.append(("%s (%d)" % (tid.comm, tid.tid), tid.freed_pages))
+ values.append(('%s (%d)' % (tid.comm, tid.tid), tid.freed_pages))
count += 1
if self._arg_limit > 0 and count >= self._arg_limit:
break
- for line in graph.graph("Per-TID Memory Deallocation", values,
- unit=" pages"):
+ for line in graph.graph('Per-TID Memory Deallocation', values,
+ unit=' pages'):
print(line)
def _print_total_alloc_freed(self):
alloc += tid.allocated_pages
freed += tid.freed_pages
- print("\nTotal memory usage:\n- %d pages allocated\n- %d pages freed" %
+ print('\nTotal memory usage:\n- %d pages allocated\n- %d pages freed' %
(alloc, freed))
def _add_arguments(self, ap):
def progressbar_setup(obj):
- if hasattr(obj, "_arg_no_progress") and obj._arg_no_progress:
+ if hasattr(obj, '_arg_no_progress') and obj._arg_no_progress:
obj.pbar = None
return
maxval=size/BYTES_PER_EVENT)
obj.pbar.start()
else:
- print("Warning: progressbar module not available, "
- "using --no-progress.", file=sys.stderr)
+ print('Warning: progressbar module not available, '
+ 'using --no-progress.', file=sys.stderr)
obj._arg_no_progress = True
obj.pbar = None
obj.event_count = 0
def progressbar_update(obj):
- if hasattr(obj, "_arg_no_progress") and \
+ if hasattr(obj, '_arg_no_progress') and \
(obj._arg_no_progress or obj.pbar is None):
return
try:
def progressbar_finish(obj):
- if hasattr(obj, "_arg_no_progress") and obj._arg_no_progress:
+ if hasattr(obj, '_arg_no_progress') and obj._arg_no_progress:
return
obj.pbar.finish()
multi_day=True),
common.ns_to_hour_nsec(end_ns, gmt=self._arg_gmt,
multi_day=True)))
- strformat = "{:<28} {:>14} {:>14} {:>14} {:>12} {:>10} {:<14}"
- print("Per-TID syscalls statistics (usec)")
+ strformat = '{:<28} {:>14} {:>14} {:>14} {:>12} {:>10} {:<14}'
+ print('Per-TID syscalls statistics (usec)')
for tid in sorted(self.state.tids.values(),
key=operator.attrgetter('total_syscalls'),
reverse=True):
continue
if tid.total_syscalls == 0:
continue
- print(strformat.format("%s (%d, tid = %d)" % (
+ print(strformat.format('%s (%d, tid = %d)' % (
tid.comm, tid.pid, tid.tid),
- "Count", "Min", "Average", "Max", "Stdev", "Return values"))
+ 'Count', 'Min', 'Average', 'Max', 'Stdev', 'Return values'))
for syscall in sorted(tid.syscalls.values(),
key=operator.attrgetter('count'),
reverse=True):
for s in syscall.rq:
sysvalues.append(s.duration)
if s.ret >= 0:
- key = "success"
+ key = 'success'
else:
try:
key = errno.errorcode[-s.ret]
else:
rets[key] = 1
if syscall.min is None:
- syscallmin = "?"
+ syscallmin = '?'
else:
- syscallmin = "%0.03f" % (syscall.min / 1000)
- syscallmax = "%0.03f" % (syscall.max / 1000)
- syscallavg = "%0.03f" % \
+ syscallmin = '%0.03f' % (syscall.min / 1000)
+ syscallmax = '%0.03f' % (syscall.max / 1000)
+ syscallavg = '%0.03f' % \
(syscall.total_duration/(syscall.count*1000))
if len(sysvalues) > 2:
- stdev = "%0.03f" % (statistics.stdev(sysvalues) / 1000)
+ stdev = '%0.03f' % (statistics.stdev(sysvalues) / 1000)
else:
- stdev = "?"
- name = syscall.name.replace("syscall_entry_", "")
- name = name.replace("sys_", "")
- print(strformat.format(" - " + name, syscall.count,
+ stdev = '?'
+ name = syscall.name.replace('syscall_entry_', '')
+ name = name.replace('sys_', '')
+ print(strformat.format(' - ' + name, syscall.count,
syscallmin, syscallavg, syscallmax,
stdev, str(rets)))
- print(strformat.format("Total:", tid.total_syscalls, "", "", "",
- "", ""))
- print("-" * 113)
+ print(strformat.format('Total:', tid.total_syscalls, '', '', '',
+ '', ''))
+ print('-' * 113)
- print("\nTotal syscalls: %d" % (self.state.syscalls["total"]))
+ print('\nTotal syscalls: %d' % (self.state.syscalls['total']))
def _reset_total(self, start_ts):
pass