Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-28 22:13:49 -05:00
commit 05756094ac
706 files changed
+135430

No files matched your search

Binary file not shown.
+32
View File
@@ -0,0 +1,32 @@
# Disassembles a function of an executable built with `sakura build -g`, beside what
# each instruction cost and the line and function it came from.
#
# python3 annotate.py PROFILE EXECUTABLE FUNCTION
#
# The profile is one costs.py has read; FUNCTION is a symbol, as `checker::slot`.
import os, pickle, re, subprocess, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import inlined
profile, executable, name = sys.argv[1], sys.argv[2], sys.argv[3]
events, own, calls, counts, found = pickle.load(open(profile + '.pkl', 'rb'))
for line in subprocess.run(['nm', '-S', executable], capture_output=True, text=True).stdout.split('\n'):
parts = line.split(None, 3)
if len(parts) != 4 or parts[3] != name:
continue
start, size = int(parts[0], 16), int(parts[1], 16)
listing = subprocess.run(['objdump', '-d', '--no-show-raw-insn', f'--start-address={start}',
f'--stop-address={start + size}', executable], capture_output=True, text=True).stdout
mapped = inlined.chains(executable, range(start, start + size))
last = None
for each in listing.split('\n'):
m = re.match(r'\s*([0-9a-f]+):\s*(.*)', each)
if not m:
continue
address = int(m.group(1), 16)
chain = inlined.frames(mapped, address)
if chain[0] != last:
print(f' ; {chain[0][1]} [{chain[0][0]}]')
last = chain[0]
print(f'{own.get(address, [0])[0]:>12,} {m.group(2)}')
break
+145
View File
@@ -0,0 +1,145 @@
# Reads a callgrind profile of an executable built with `sakura build -g` and prints
# its costs with inlined code counted where it came from.
#
# valgrind --tool=callgrind --dump-instr=yes --compress-pos=no --compress-strings=no \
# --callgrind-out-file=PROFILE EXECUTABLE ARGS...
# python3 costs.py PROFILE EXECUTABLE [EVENT [MODE [COUNT [FUNCTION]]]]
#
# EVENT is one callgrind counted, `Ir` by default; with `--cache-sim=yes
# --branch-sim=yes` there are also `D1mr`, `DLmw`, `I1mr`, `Bcm`, and the others.
# MODE is one of:
# fn self cost by source function
# incl inclusive cost by source function (recursion counts more than once)
# line self cost by source line
# sym self cost by symbol, the function the code was emitted in
# callees F what F's code calls, inlined code included
# callers F the call sites of F, where it is called rather than inlined
# inlined F where F's code was inlined
# lines F the lines of F
# users REGEX the cost of functions matching REGEX by the first frame outside
# them and std that led there, which is the analyzer code using them
# calls out-of-line calls of each function, and its instructions per call
# The mapping is cached beside the profile, as PROFILE.pkl.
import collections, os, pickle, re, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import inlined
profile, executable = sys.argv[1], sys.argv[2]
event = sys.argv[3] if len(sys.argv) > 3 else 'Ir'
mode = sys.argv[4] if len(sys.argv) > 4 else 'fn'
count = int(sys.argv[5]) if len(sys.argv) > 5 else 40
target = sys.argv[6] if len(sys.argv) > 6 else None
cache = profile + '.pkl'
if os.path.exists(cache) and os.path.getmtime(cache) > os.path.getmtime(profile):
events, own, calls, counts, found = pickle.load(open(cache, 'rb'))
else:
events, own, calls, counts = [], {}, [], collections.Counter()
callee = None
pending = False
positions = 1
for line in open(profile):
if line.startswith('positions:'):
positions = len(line.split()) - 1
elif line.startswith('events:'):
events = line.split()[1:]
elif line.startswith('cfn='):
callee = line[4:].strip()
elif line.startswith('calls='):
counts[callee] += int(line.split()[0][6:])
pending = True
elif line.startswith('0x'):
parts = line.split()
address = int(parts[0], 16)
# With --dump-line=yes a line number follows the address.
numbers = [int(x) for x in parts[positions:]]
numbers += [0] * (len(events) - len(numbers))
if pending:
calls.append((address, callee, numbers))
pending = False
elif address in own:
own[address] = [a + b for a, b in zip(own[address], numbers)]
else:
own[address] = numbers
found = inlined.chains(executable, list(own) + [a for a, _, _ in calls])
pickle.dump((events, own, calls, counts, found), open(cache, 'wb'))
index = events.index(event)
total = sum(c[index] for c in own.values()) or 1
def show(title, counter):
print(f'== {title} ({event}, total {total:,})')
for key, value in counter.most_common(count):
print(f'{100 * value / total:6.2f}% {value:>13,} {key[:110]}')
def outside(chain, pattern):
for function, location in chain:
if not pattern.search(function) and not location.startswith('std/'):
return function + ' @ ' + location
return None
result = collections.Counter()
if mode in ('fn', 'line', 'sym'):
for address, cost in own.items():
chain = inlined.frames(found, address)
key = {'fn': chain[0][0], 'line': chain[0][1], 'sym': chain[-1][0]}[mode]
result[key] += cost[index]
show({'fn': 'self cost by source function', 'line': 'self cost by line', 'sym': 'self cost by symbol'}[mode], result)
elif mode == 'incl':
for address, cost in own.items():
for function in set(f for f, _ in inlined.frames(found, address)):
result[function] += cost[index]
for address, called, cost in calls:
for function in set(f for f, _ in inlined.frames(found, address)):
if function != called:
result[function] += cost[index]
show('inclusive cost by source function', result)
elif mode == 'callees':
for address, called, cost in calls:
names = [f for f, _ in inlined.frames(found, address)]
if target in names:
within = names[:names.index(target)]
result[called + (' via ' + '/'.join(reversed(within)) if within else '')] += cost[index]
show(f'calls made by {target}, inclusive', result)
elif mode == 'callers':
for address, called, cost in calls:
if called == target:
chain = inlined.frames(found, address)
result[chain[0][0] + ' @ ' + chain[0][1]] += cost[index]
show(f'calls of {target}, inclusive, by call site', result)
elif mode == 'inlined':
for address, cost in own.items():
chain = inlined.frames(found, address)
names = [f for f, _ in chain]
if target in names and names.index(target) + 1 < len(names):
outer = chain[names.index(target) + 1]
result[outer[0] + ' @ ' + outer[1]] += cost[index]
show(f'{target} inlined into', result)
elif mode == 'lines':
for address, cost in own.items():
chain = inlined.frames(found, address)
if chain[0][0] == target:
result[chain[0][1]] += cost[index]
show(f'lines of {target}', result)
elif mode == 'users':
pattern = re.compile(target)
for address, cost in own.items():
chain = inlined.frames(found, address)
if pattern.search(chain[0][0]):
user = outside(chain, pattern)
if user:
result[user] += cost[index]
for address, called, cost in calls:
chain = inlined.frames(found, address)
if pattern.search(called) and not pattern.search(chain[-1][0]):
user = outside(chain, pattern)
if user:
result[user] += cost[index]
show(f'/{target}/ by the code using it', result)
elif mode == 'calls':
symbols = collections.Counter()
for address, cost in own.items():
symbols[inlined.frames(found, address)[-1][0]] += cost[0]
print(' calls instructions per call function')
for function, n in counts.most_common(count):
print(f'{n:>10,} {symbols[function]:>12,} {symbols[function] / n:8.1f} {function}')
+78
View File
@@ -0,0 +1,78 @@
// Runs a program pinned to one processor and counts its work with the processor's
// own counters, which need no kernel profiling support beyond `perf_event_open`.
//
// cc -O2 -o count count.c
// count CPU PROGRAM ARGS...
//
// Prints to the standard error, on one line: the wall time in seconds, the peak
// resident memory in KB, the instructions and the cycles the program and its threads
// ran outside the kernel, and its exit status. A CPU below 0 doesn't pin it. The
// program's output is discarded.
//
// The counters are the performance cores' (`cpu_core`), as this processor's efficiency
// cores count no cycles, so pin to a performance core. They need
// `/proc/sys/kernel/perf_event_paranoid` at 2 or less.
#define _GNU_SOURCE
#include <fcntl.h>
#include <linux/perf_event.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
static int open_counter(pid_t pid, unsigned long long type, unsigned long long config) {
struct perf_event_attr a;
memset(&a, 0, sizeof a);
a.size = sizeof a;
a.type = PERF_TYPE_HARDWARE;
a.config = (type << 32) | config;
a.disabled = 1;
a.enable_on_exec = 1;
a.inherit = 1;
a.exclude_kernel = 1;
a.exclude_hv = 1;
return (int)syscall(SYS_perf_event_open, &a, pid, -1, -1, 0);
}
int main(int argc, char **argv) {
int cpu = atoi(argv[1]);
FILE *f = fopen("/sys/bus/event_source/devices/cpu_core/type", "r");
unsigned long long type = 0;
if (f) { if (fscanf(f, "%llu", &type) != 1) type = 0; fclose(f); }
int go[2];
if (pipe(go)) return 1;
struct timespec t0, t1;
pid_t pid = fork();
if (pid == 0) {
if (cpu >= 0) {
cpu_set_t set; CPU_ZERO(&set); CPU_SET(cpu, &set);
sched_setaffinity(0, sizeof set, &set);
}
close(go[1]);
char c; if (read(go[0], &c, 1) != 1) _exit(127);
int null = open("/dev/null", O_WRONLY);
dup2(null, 1);
execvp(argv[2], argv + 2);
_exit(127);
}
close(go[0]);
int ins = open_counter(pid, type, PERF_COUNT_HW_INSTRUCTIONS);
int cyc = open_counter(pid, type, PERF_COUNT_HW_CPU_CYCLES);
clock_gettime(CLOCK_MONOTONIC, &t0);
if (write(go[1], "x", 1) != 1) return 1;
int status; struct rusage ru;
wait4(pid, &status, 0, &ru);
clock_gettime(CLOCK_MONOTONIC, &t1);
long long ni = -1, nc = -1;
if (ins >= 0 && read(ins, &ni, sizeof ni) != sizeof ni) ni = -1;
if (cyc >= 0 && read(cyc, &nc, sizeof nc) != sizeof nc) nc = -1;
double wall = (t1.tv_sec - t0.tv_sec) + (t1.tv_nsec - t0.tv_nsec) / 1e9;
fprintf(stderr, "%.4f %ld %lld %lld %d\n", wall, ru.ru_maxrss, ni, nc,
WIFEXITED(status) ? WEXITSTATUS(status) : -1);
return 0;
}
+40
View File
@@ -0,0 +1,40 @@
# Maps code addresses of an executable built with `sakura build -g` to the functions
# they were inlined from, through `addr2line -i`, which reads the executable's
# `.petal` file. Shared by the scripts beside it.
import os, re, subprocess
# Paths are shown relative to the current directory, and to the standard library
# where SAKURA_STD names it.
_prefixes = [os.getcwd().rstrip('/') + '/']
if os.environ.get('SAKURA_STD'):
_prefixes.append(os.environ['SAKURA_STD'].rstrip('/') + '/')
def _short(location):
location = re.sub(r' \(discriminator.*\)', '', location)
for i, prefix in enumerate(_prefixes):
if location.startswith(prefix):
return ('std/' if i > 0 else '') + location[len(prefix):]
return location
def chains(executable, addresses):
"""Each address's frames, innermost first: (function, file:line)."""
addresses = sorted(set(addresses))
out = subprocess.run(['addr2line', '-e', executable, '-a', '-f', '-i'],
input='\n'.join(hex(a) for a in addresses),
capture_output=True, text=True).stdout.split('\n')
found, current, i = {}, None, 0
while i < len(out):
line = out[i]
if line.startswith('0x'):
current = int(line, 16)
found[current] = []
i += 1
elif current is not None and i + 1 < len(out):
found[current].append((line, _short(out[i + 1])))
i += 2
else:
i += 1
return found
def frames(found, address):
return found.get(address) or [('??', '??:0')]
+52
View File
@@ -0,0 +1,52 @@
# Classifies the instructions a callgrind profile counted by what they do, which
# shows how much of the code is moving values between frame slots and registers,
# calling, and checking, rather than computing.
#
# python3 kinds.py PROFILE EXECUTABLE
#
# The profile is one costs.py has read.
import collections, os, pickle, re, subprocess, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
profile, executable = sys.argv[1], sys.argv[2]
events, own, calls, counts, found = pickle.load(open(profile + '.pkl', 'rb'))
listing = subprocess.run(['objdump', '-d', '--no-show-raw-insn', executable], capture_output=True, text=True).stdout
instructions, order = {}, []
for line in listing.splitlines():
m = re.match(r'\s*([0-9a-f]+):\s+(.*)$', line)
if m:
address = int(m.group(1), 16)
instructions[address] = m.group(2).strip()
order.append(address)
following = {order[i]: order[i + 1] for i in range(len(order) - 1)}
def kind(text, after):
if text.startswith('rep stos'): return 'zeroing: rep stos'
if text.startswith('rep movs'): return 'copying: rep movs'
if re.match(r'movq\s+\$0x0,-?(0x[0-9a-f]+)?\(%rbx\)', text): return 'zeroing: slot'
if text.startswith(('push %rbp', 'mov %rsp,%rbp', 'leave', 'ret')): return 'call: frame link'
if re.match(r'(add|sub)\s+\$0x[0-9a-f]+,%rbx$', text): return 'call: moving rbx'
if text.startswith('call'): return 'call: call'
# The prologue's check of the frames' limit: lea from rbx, then cmp with a global.
if re.match(r'lea\s+-?(0x[0-9a-f]+)?\(%rbx\),%rax$', text) and re.match(r'cmp\s+0x[0-9a-f]+,%rax$', after): return 'call: stack check'
if re.match(r'cmp\s+0x[0-9a-f]+,%rax$', text): return 'call: stack check'
if re.match(r'test\s+(%\w+),\1$', text) and after.startswith('jne'): return 'null check'
if re.search(r'\(%rbx\)', text) and text.startswith('mov'):
return 'slot: store' if re.match(r'mov\w*\s+%\w+,', text) else 'slot: load'
if re.match(r'lea\s+-?(0x[0-9a-f]+)?\(%rbx\)', text): return 'slot: address'
if re.match(r'mov\s+%\w+,%\w+$', text): return 'register copy'
if re.match(r'mov\w*\s+\$', text): return 'constant'
if re.match(r'mov\w*\s+[^,]*\([^)]*\),%\w+$', text): return 'load through a pointer'
if re.match(r'mov\w*\s+%\w+,[^,]*\(', text): return 'store through a pointer'
if text.startswith('j'): return 'branch'
if text.startswith(('cmp', 'test')): return 'compare'
return 'computing: ' + text.split()[0]
result = collections.Counter()
for address, cost in own.items():
text = instructions.get(address, '?')
result[kind(text, instructions.get(following.get(address), ''))] += cost[0]
total = sum(result.values()) or 1
for name, value in result.most_common(30):
print(f'{value:>14,} {100 * value / total:5.1f}% {name}')
print(f'{total:>14,} total')
+110
View File
@@ -0,0 +1,110 @@
# Times the compilers at their work, in turns, through `count`, as docs/performance.md
# measures them: each checking and building the rebuild's sources of its day, checking a
# one-line program, and running the rebuild's compiler on its VM.
#
# cc -O2 -o count count.c
# python3 -I measure.py WORK [GROUP...]
#
# WORK is a directory holding what's measured, laid out as below, and GROUP any of
# `hello`, `check`, `build`, `vm` and `threads` (all by default). Prints a line for
# each command and writes them to WORK/results.json.
#
# count the counter, built from count.c
# c_start/sakura C as it was, and c_start/std its std
# r_start/ the rebuild's sources and std as they were
# r_start_c the rebuild as they were, built by c_start/sakura
# r_start_s2 the same, its own fixed point
# c_now/sakura C as it is, and c_now/std its std
# r_now/ the rebuild's sources and std as they are, with `std::json` and
# `std::args`, packages since 2026-10-24, copied back into its std
# as `std/json` and `std/args`, since C can't take `--lib std::json`
# r_now_c the rebuild as it is, built by c_now/sakura
# r_now_s2 the same, its own fixed point
#
# Each group's commands are pinned to CPU (2 by default, or $CPU), but for `threads`,
# which lets the rebuild run its threads where it will.
import glob, json, os, statistics, subprocess, sys
W = os.path.abspath(sys.argv[1])
CPU = int(os.environ.get("CPU", "2"))
def sources(root, dirs):
found = ["entry.sakura"]
for d in dirs:
found += sorted(os.path.relpath(f, root) for f in glob.glob(f"{root}/{d}/**/*.sakura", recursive=True))
return found
ST, NW = W + "/r_start", W + "/r_now"
SS = sources(ST, ["analyzer", "compiler", "machine", "native"])
SN = sources(NW, ["analyzer", "compiler", "machine", "native", "server"])
STDS, STDN = ST + "/std", NW + "/std"
CS, CN = W + "/c_start/sakura", W + "/c_now/sakura"
RS, RSC = W + "/r_start_s2", W + "/r_start_c"
RN, RNC = W + "/r_now_s2", W + "/r_now_c"
HS, HN, OUT = W + "/hello_start.sakura", W + "/hello_now.sakura", W + "/out.bin"
with open(HS, "w") as f: f.write("import std::io;\n\ndef main(): void { io::println(\"hi\"); }\n")
with open(HN, "w") as f: f.write("import std::io;\n\ndef main(): void { io::println(\"hi\"); }\n")
groups = {
"hello": (21, [
("start C checks one line", W, [CS, "check", "--std", W + "/c_start/std", HS]),
("start rebuild checks one line", W, [RS, "--std", STDS, HS]),
("now C checks one line", W, [CN, "check", "--std", W + "/c_now/std", HN]),
("now rebuild checks one line -j1", W, [RN, "check", "-j", "1", "--std", STDN, HN]),
]),
"check": (9, [
("start C checks rebuild", ST, [CS, "check", "--std", STDS] + SS),
("start rebuild checks itself", ST, [RS, "--std", STDS] + SS),
("now C checks rebuild", NW, [CN, "check", "--std", STDN] + SN),
("now rebuild checks itself -j1", NW, [RN, "check", "-j", "1", "--std", STDN] + SN),
]),
"build": (5, [
("start C builds rebuild", ST, [CS, "build", "--std", STDS, "-O2", "-o", OUT] + SS),
("start rebuild (self-built) builds itself", ST, [RS, "build", "--std", STDS, "-O2", "-o", OUT] + SS),
("start rebuild (C-built) builds itself", ST, [RSC, "build", "--std", STDS, "-O2", "-o", OUT] + SS),
("now C builds rebuild", NW, [CN, "build", "--std", STDN, "-O2", "-o", OUT] + SN),
("now rebuild (self-built) builds itself -j1", NW, [RN, "build", "-j", "1", "--std", STDN, "-O2", "-o", OUT] + SN),
("now rebuild (C-built) builds itself -j1", NW, [RNC, "build", "-j", "1", "--std", STDN, "-O2", "-o", OUT] + SN),
]),
"vm": (3, [
("start C VM runs rebuild checking one line", ST, [CS, "run", "--std", STDS] + SS + ["--", "--std", STDS, HS]),
("start rebuild VM runs itself checking one line", ST, [RS, "run", "--std", STDS] + SS + ["--", "--std", STDS, HS]),
("now C VM runs rebuild checking one line", NW, [CN, "run", "--std", STDN] + SN + ["--", "check", "--std", STDN, HN]),
("now rebuild VM runs itself checking one line -j1", NW, [RN, "run", "-j", "1", "--std", STDN] + SN + ["--", "check", "-j", "1", "--std", STDN, HN]),
]),
"threads": (5, [
("now rebuild builds itself, default threads", NW, [RN, "build", "--std", STDN, "-O2", "-o", OUT] + SN),
("now rebuild builds itself -j1 (unpinned)", NW, [RN, "build", "-j", "1", "--std", STDN, "-O2", "-o", OUT] + SN),
("now rebuild checks itself, default threads", NW, [RN, "check", "--std", STDN] + SN),
]),
}
def once(cpu, cwd, argv):
run = subprocess.run([W + "/count", str(cpu)] + argv, cwd=cwd, stderr=subprocess.PIPE, text=True)
wall, rss, ins, cyc, status = run.stderr.strip().splitlines()[-1].split()
if status != "0":
print("FAILED", " ".join(argv[:3]), run.stderr[-400:], file=sys.stderr)
return float(wall), int(rss), int(ins), int(cyc)
results = {}
for group in sys.argv[2:] or list(groups):
rounds, commands = groups[group]
cpu = -1 if group == "threads" else CPU
runs = {name: [] for name, _, _ in commands}
for _ in range(rounds):
for name, cwd, argv in commands:
runs[name].append(once(cpu, cwd, argv))
for name, rs in runs.items():
walls = [r[0] for r in rs]
results[name] = {
"best": min(walls), "median": statistics.median(walls),
"rss_mb": max(r[1] for r in rs) / 1024,
"instructions": statistics.median(r[2] for r in rs),
"cycles": statistics.median(r[3] for r in rs), "runs": rounds,
}
r = results[name]
print(f"{name:50s} best {r['best']:7.3f}s median {r['median']:7.3f}s "
f"rss {r['rss_mb']:6.1f}MB instr {r['instructions'] / 1e9:6.3f}G "
f"cycles {r['cycles'] / 1e9:6.3f}G", flush=True)
with open(W + "/results.json", "w") as f: json.dump(results, f, indent=1)
if os.path.exists(OUT): os.remove(OUT)
+69
View File
@@ -0,0 +1,69 @@
// Samples a program's instruction pointer and its chain of return addresses with
// ptrace, which needs no kernel profiling support.
//
// cc -O2 -o sampler sampler.c
// sampler OUT INTERVAL_US PROGRAM ARGS...
//
// Writes one line per sample to OUT: the instruction pointer, then each return
// address the `rbp` chain gives, in hex. The program's output is discarded.
#define _GNU_SOURCE
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ptrace.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char **argv) {
FILE *out = fopen(argv[1], "w");
long interval = atol(argv[2]);
pid_t pid = fork();
if (pid == 0) {
int null = open("/dev/null", O_WRONLY); dup2(null, 1);
ptrace(PTRACE_TRACEME, 0, 0, 0);
raise(SIGSTOP);
execv(argv[3], argv + 3);
_exit(127);
}
int status;
waitpid(pid, &status, 0);
ptrace(PTRACE_SETOPTIONS, pid, 0, PTRACE_O_EXITKILL);
ptrace(PTRACE_CONT, pid, 0, 0);
// Wait for the exec stop.
waitpid(pid, &status, 0);
ptrace(PTRACE_CONT, pid, 0, 0);
long samples = 0;
for (;;) {
struct timespec ts = { 0, interval * 1000 };
nanosleep(&ts, 0);
if (kill(pid, SIGSTOP) != 0) break;
if (waitpid(pid, &status, 0) < 0) break;
if (WIFEXITED(status) || WIFSIGNALED(status)) break;
int sig = WSTOPSIG(status);
if (sig != SIGSTOP) { ptrace(PTRACE_CONT, pid, 0, sig); continue; }
struct user_regs_struct r;
if (ptrace(PTRACE_GETREGS, pid, 0, &r) == 0) {
fprintf(out, "%llx", r.rip);
unsigned long bp = r.rbp;
for (int i = 0; i < 400 && bp; i++) {
errno = 0;
long ret = ptrace(PTRACE_PEEKDATA, pid, bp + 8, 0);
long next = ptrace(PTRACE_PEEKDATA, pid, bp, 0);
if (errno) break;
fprintf(out, " %lx", ret);
if ((unsigned long)next <= bp) break;
bp = next;
}
fputc('\n', out);
samples++;
}
ptrace(PTRACE_CONT, pid, 0, 0);
}
fclose(out);
fprintf(stderr, "%ld samples\n", samples);
return 0;
}
+87
View File
@@ -0,0 +1,87 @@
# Reads the samples `sampler` wrote of an executable built with `sakura build -g`,
# and prints where the time went, with inlined code counted where it came from.
#
# python3 samples.py SAMPLES EXECUTABLE [MODE [COUNT [REGEX]]] [--profile PROFILE]
#
# MODE is one of:
# fn time by source function; with `--profile`, a callgrind profile of
# the same executable that costs.py has read, also its share of
# instructions and the ratio of the two, which is high where the
# code waits on memory, mispredicted branches, or the kernel
# incl time by every function on the stack
# line time by source line
# users REGEX time in functions matching REGEX by the first frame outside them
# and std that led there
import collections, os, pickle, re, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import inlined
arguments = sys.argv[1:]
profile = None
if '--profile' in arguments:
at = arguments.index('--profile')
profile = arguments[at + 1]
del arguments[at:at + 2]
samples, executable = arguments[0], arguments[1]
mode = arguments[2] if len(arguments) > 2 else 'fn'
count = int(arguments[3]) if len(arguments) > 3 else 40
target = arguments[4] if len(arguments) > 4 else None
rows = [[int(x, 16) for x in line.split()] for line in open(samples) if line.strip()]
addresses = set()
for row in rows:
addresses.add(row[0])
addresses.update(a - 1 for a in row[1:])
found = inlined.chains(executable, addresses)
n = len(rows) or 1
def stack(row):
chain = list(inlined.frames(found, row[0]))
for a in row[1:]:
chain += found.get(a - 1) or []
return chain
result = collections.Counter()
if mode == 'fn':
for row in rows:
result[inlined.frames(found, row[0])[0][0]] += 1
shares = collections.Counter()
if profile:
events, own, calls, counts, mapped = pickle.load(open(profile + '.pkl', 'rb'))
for address, cost in own.items():
shares[inlined.frames(mapped, address)[0][0]] += cost[0]
whole = sum(shares.values()) or 1
print(f'{len(rows)} samples time instr ratio function')
for function, c in result.most_common(count):
t, s = 100 * c / n, 100 * shares[function] / whole
print(f' {t:6.2f}% {s:6.2f}% {t / s if s else 0:5.2f} {function[:90]}')
else:
for function, c in result.most_common(count):
print(f'{100 * c / n:6.2f}% {function[:100]}')
elif mode == 'incl':
for row in rows:
for function in set(f for f, _ in stack(row)):
result[function] += 1
for function, c in result.most_common(count):
print(f'{100 * c / n:6.2f}% {function[:100]}')
elif mode == 'line':
for row in rows:
result[inlined.frames(found, row[0])[0][1]] += 1
for location, c in result.most_common(count):
print(f'{100 * c / n:6.2f}% {location[:100]}')
elif mode == 'users':
pattern = re.compile(target)
hits = 0
for row in rows:
if not pattern.search(inlined.frames(found, row[0])[0][0]):
continue
hits += 1
user = '?'
for function, location in stack(row):
if not pattern.search(function) and not location.startswith('std/'):
user = function + ' @ ' + location
break
result[user] += 1
print(f'== {100 * hits / n:.2f}% of the time in /{target}/, by the code using it')
for user, c in result.most_common(count):
print(f'{100 * c / n:6.2f}% {user[:110]}')