diff --git a/core/tools/alloc.py b/core/tools/alloc.py index 729acbee1e..a50e7c9f66 100755 --- a/core/tools/alloc.py +++ b/core/tools/alloc.py @@ -1,8 +1,11 @@ #!/usr/bin/env python3 +from pathlib import Path from types import SimpleNamespace import click +HERE = Path(__file__).parent.resolve() + def parse_alloc_data(alloc_data): parsed_data = {} @@ -30,17 +33,23 @@ def cli(ctx, alloc_data, type): ctx.obj = SimpleNamespace(data=parse_alloc_data(alloc_data), type=type) +def _normalize_filename(filename): + if filename.startswith("src/"): + return filename[4:] + return filename + + @cli.command() @click.pass_obj @click.argument("filename") def annotate(obj, filename): + filename = _normalize_filename(filename) + if obj.type == "total": alloc_str = lambda line: str(line["total_allocs"]) else: alloc_str = lambda line: "{:.2f}".format(line["avg_allocs"]) - if filename.startswith("src/"): - filename = filename[4:] filedata = obj.data[filename] linedata = {lineno: alloc_str(line) for lineno, line in filedata.items()} @@ -53,30 +62,110 @@ def annotate(obj, filename): print(f"{linecount:>{maxlen}} {line}", end="") +def _list(obj, sort_by="avg_allocs", reverse=False): + return sorted( + ( + ( + filename, + sum(line["avg_allocs"] for line in lines.values()), + sum(line["total_allocs"] for line in lines.values()), + ) + for filename, lines in obj.data.items() + ), + key=lambda x: x[1 if sort_by == "avg_allocs" else 2], + reverse=reverse, + ) + + @cli.command() @click.pass_obj @click.option("-r", "--reverse", is_flag=True) def list(obj, reverse): if obj.type == "total": field = "total_allocs" - field_fmt = "{}" + format_num = lambda l: "{}".format(l[2]) else: field = "avg_allocs" - field_fmt = "{:.2f}" + format_num = lambda l: "{:.2f}".format(l[1]) - file_sums = { - filename: sum(line[field] for line in lines.values()) - for filename, lines in obj.data.items() - } + file_sums = _list(obj, field, reverse) - maxlen = max(len(field_fmt.format(l)) for l in file_sums.values()) - - for filename, file_sum in sorted( - file_sums.items(), key=lambda x: x[1], reverse=reverse - ): - num_str = field_fmt.format(file_sum) + maxlen = max(len(format_num(l)) for l in file_sums) + for l in file_sums: + num_str = format_num(l) + filename = l[0] print(f"{num_str:>{maxlen}} {filename}") +class HtmlTable: + def __init__(self, f): + self.f = f + + def __enter__(self): + self.f.write("