Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-12-06 13:52:57 -06:00
commit 528ccf1523
782 files changed
+145156

No files matched your search

+204
View File
@@ -0,0 +1,204 @@
#! @file corpus.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the runner of the corpus, the programs of `tests/programs`: each is
#! run by a command given, and what it writes and how it stops are compared
#! with `NAME.out` beside it, so the C compiler and the rebuild are held to one
#! corpus. Run it from the root of the repository:
#!
#! sakura run --lib std=STD tools/corpus.sakura -- [--write] [--only TEXT] [--dir DIR] COMMAND...
#!
#! The command is given each program's path after its own words, as
#! `sakura run --lib std=STD`, the C compiler's `sakura run --std STD`, or the
#! rebuild's `entry run --lib std=STD` built as an executable. `--write` writes what each program gives as its `NAME.out`
#! rather than comparing, as the C compiler does to make them, `--only TEXT`
#! runs only the programs whose name holds the text, and `--dir DIR` runs those
#! of another directory: `tests/checked`, whose programs stop only where the
#! program checks, as `run` and `build --checks` make it, and `tests/memory`,
#! whose programs are run with `run --checks`.
#!
#! `NAME.out` holds what the program wrote to its output, and, where it stopped
#! with any status but 0 or wrote to its error, a line `--- exit N`, or
#! `--- signal N`, after it, then what it wrote to its error.
import std::io;
import std::process;
import system;
#! Where the programs are, from the root of the repository, unless `--dir`
#! names another directory.
const corpus: strview = "tests/programs";
def main(args: span<strview>): void {
var writes := false;
var only := string::new(nothing {});
var directory: strview = corpus;
var command := vector::<strview>::new();
var i := 0u;
while i < args.length {
val arg := args.at(i);
if command.length == 0 && arg == "--write" {
writes = true;
} else if command.length == 0 && arg == "--only" && i + 1 < args.length {
i++;
only = string::from(args.at(i), nothing {});
} else if command.length == 0 && arg == "--dir" && i + 1 < args.length {
i++;
directory = args.at(i);
} else {
command.append(arg);
}
i++;
}
if command.length == 0 {
system::fd::stderr.put("corpus: give the command each program is run by, as `sakura run --lib std=../std --lib system=../system/system`\n");
exit(2);
}
var names := program_names(directory);
var passed := 0u;
var failed := 0u;
for &name in names {
continue if only.length != 0 && !contains(name.span, only.span);
val program := $"{directory}/{name}.sakura";
val expected_at := $"{directory}/{name}.out";
var got := run(command.span, program.span);
var at := path::parse(expected_at.span) else (_) { continue; };
if writes {
_ = io::write_file(&at, got.span);
continue;
}
var expected := io::read_file(&at) else (_) {
println($"[ FAIL ] {name}: it has no `{name}.out`");
failed++;
continue;
};
if expected.span == got.span {
passed++;
continue;
}
failed++;
println($"[ FAIL ] {name}");
show_difference(expected.span, got.span);
}
if writes {
println($"wrote what {names.length} programs give");
return;
}
println($"{passed} passed, {failed} failed");
exit(failed == 0 ? 0 : 1);
}
#! The name of each program of a directory, without `.sakura`, in order.
#! @param directory The directory.
#! @returns The names.
def program_names(directory: strview): vector<string> {
var made := vector::<string>::new();
var at := path::parse(directory) else (_) { return made; };
var listing := io::directory::open(&at) else (_) { return made; };
while listing.next() is some(each) {
val name := each.name;
continue if name.length <= 7 || name.substr(name.length - 7, 7) != ".sakura";
made.append(string::from(name.substr(0, name.length - 7), nothing {}));
}
# In order, so the runs read the same each time.
var sorted := vector::<string>::new();
for &each in made {
var at := sorted.length;
while at > 0 && sorted.at(at - 1).compare(each.span) > 0 {
at--;
}
sorted.insert_at(at, string::copy_of(&each));
}
return sorted;
}
#! Runs a program by the command, and gives what it wrote and how it stopped,
#! as `NAME.out` holds them.
#! @param command The command's words.
#! @param program The program's path.
#! @returns The text.
def run(command: span<strview>, program: strview): string {
var started := process::command::new(command.at(0));
for i in 1..command.length {
started.argument(command.at(i));
}
started.argument(program);
var made := string::new(nothing {});
val got := started.capture() else (why) {
made.append($"--- not started: {why}\n");
return made;
};
made.append(got.output.span);
var stopped := string::new(nothing {});
if got.status is exited(code) {
if code != 0 {
stopped.append($"--- exit {code}");
}
} else if got.status is signaled(number) {
stopped.append($"--- signal {number}");
}
if stopped.length == 0 && got.error.length != 0 {
stopped.append("--- exit 0");
}
if stopped.length != 0 {
made.append("\n");
made.append(stopped.span);
made.append("\n");
made.append(got.error.span);
}
return made;
}
#! Whether text holds other text.
#! @param text The text searched.
#! @param piece The text looked for.
#! @returns Whether it does.
def contains(text: strview, piece: strview): bool {
return true if piece.length == 0;
return false if piece.length > text.length;
for i in 0..text.length - piece.length + 1 {
return true if text.substr(i, piece.length) == piece;
}
return false;
}
#! Shows the first line where what a program gave differs from what was
#! expected.
#! @param expected What was expected.
#! @param got What it gave.
def show_difference(expected: strview, got: strview): void {
var line := 1u;
var at := 0u;
while at < expected.length && at < got.length && expected.at(at) == got.at(at) {
if expected.at(at) == '\n' {
line++;
}
at++;
}
println($" line {line}:");
println($" expected: {line_at(expected, at)}");
println($" got: {line_at(got, at)}");
}
#! The line of text holding a byte, without its line break.
#! @param text The text.
#! @param at The byte.
#! @returns The line.
def line_at(text: strview, at: u64): strview {
var start := at < text.length ? at : text.length;
while start > 0 && text.at(start - 1) != '\n' {
start--;
}
var end := start;
while end < text.length && text.at(end) != '\n' {
end++;
}
return text.substr(start, end - start);
}
+96
View File
@@ -0,0 +1,96 @@
#! @file function.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the probe of what a call costs, as `docs/performance.md` records
#! it: `t = t ^ f(i)` over many calls, `f` held each way a program holds a
#! callable.
#! Build it as an executable and run it on one core, or run it in the machine
#! with fewer calls:
#!
#! sakura build --lib std=../std -O2 -o calls tools/function.sakura
#! taskset -c 2 ./calls
#! taskset -c 2 sakura run --lib std=../std tools/function.sakura -- 10000000
#!
#! A functor a `function` holds should cost what a function value does.
import std::io;
import std::time;
# A functor of two words, which a function holds in its buffer.
struct small : invokable<def(i64): i64> { var a: i64; var b: i64; }
def small::invoke(&mut this, x: i64): i64 { return x + this.a * this.b; }
# A functor of four words, which a function holds in a box.
struct large : invokable<def(i64): i64> { var a: i64; var b: i64; var pad: u64[2]; }
def large::invoke(&mut this, x: i64): i64 { return x + this.a * this.b; }
# Each callable is kept in a global, read where it is called, so that nothing
# calling it knows which it is.
var a_small: small;
var a_value: maybe<def(i64): i64> = nothing {};
var a_trait: maybe<&mut invokable<def(i64): i64>> = nothing {};
var in_place: function<def(i64): i64>;
var boxed: function<def(i64): i64>;
var a_lambda: function<def(i64): i64>;
def with_generic<F>(f: &mut F, calls: i64): i64 where F: invokable<def(i64): i64> {
var t: i64 = 0;
for i in 0..calls { t = t ^ f(i); }
return t;
}
def with_value(f: def(i64): i64, calls: i64): i64 {
var t: i64 = 0;
for i in 0..calls { t = t ^ f(i); }
return t;
}
def with_trait(f: &mut invokable<def(i64): i64>, calls: i64): i64 {
var t: i64 = 0;
for i in 0..calls { t = t ^ f(i); }
return t;
}
def with_function(f: &function<def(i64): i64>, calls: i64): i64 {
var t: i64 = 0;
for i in 0..calls { t = t ^ f(i); }
return t;
}
# Prints how long each call took, in nanoseconds.
def report(name: strview, start: time::instant, calls: i64, t: i64): void {
val ns := (time::instant::now() - start) / time::nanoseconds(1);
println($"{name}: {ns / (calls as f64)} ns ({t})");
}
@allow def main(args: span<strview>): void {
var calls: i64 = 300000000;
if args.length != 0 {
calls = integer::parse::<i64>(args[0]) else { return; };
}
val a := 3;
val b := 5;
a_small = small { a = 3, b = 5 };
a_value = def(x: i64): i64 => x + a * b;
a_trait = &mut a_small;
in_place = function::new(small { a = 3, b = 5 });
boxed = function::new(large { a = 3, b = 5 });
a_lambda = function::new(def(x: i64): i64 => x + a * b);
val value := a_value else { return; };
val by_trait := a_trait else { return; };
var start := time::instant::now();
report("a generic F, inlined", start, calls, with_generic(&mut a_small, calls));
start = time::instant::now();
report("a function value, its lambda using two locals", start, calls, with_value(value, calls));
start = time::instant::now();
report("a trait reference to invokable", start, calls, with_trait(by_trait, calls));
start = time::instant::now();
report("a function holding a functor of 16 bytes", start, calls, with_function(&in_place, calls));
start = time::instant::now();
report("a function holding a functor of 32 bytes, boxed", start, calls, with_function(&boxed, calls));
start = time::instant::now();
report("a function holding a function value", start, calls, with_function(&a_lambda, calls));
}
+121
View File
@@ -0,0 +1,121 @@
#! @file iterators.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the probe of what iterators cost: one sum, of the squares of the
#! even numbers among the first N, worked out by loops written out and by
#! adapters, over a vector and over a range, each ten times. Build it as an
#! executable, as its measure is of the code a compiler makes, and run it on
#! one core:
#!
#! sakura build --lib std=STD -O2 -o iterators tools/iterators.sakura
#! taskset -c 2 ./iterators [N]
#!
#! N is 10,000,000 where it is not given. The measure the iterators plan set is
#! the adapters given functors within 10% of `for &x in v`, which the last line
#! says.
import std::io;
import std::time;
#! Tests an element a view's iterator gives, a reference, by reference.
struct is_even : invokable<def(& &u64): bool> {}
def is_even::invoke(&mut this, x: & &u64): bool { return x % 2 == 0; }
#! Squares an element a view's iterator gives.
struct square : invokable<def(&u64): u64> {}
def square::invoke(&mut this, x: &u64): u64 { return x * x; }
#! Tests a number a range gives, by reference.
struct is_even_number : invokable<def(&u64): bool> {}
def is_even_number::invoke(&mut this, x: &u64): bool { return x % 2 == 0; }
#! Squares a number a range gives.
struct square_number : invokable<def(u64): u64> {}
def square_number::invoke(&mut this, x: u64): u64 { return x * x; }
def counted(n: u64): u64 {
var total: u64 = 0;
for x in 0..n {
if x % 2 == 0 { total += x * x; }
}
return total;
}
def referred(v: &vector<u64>): u64 {
var total: u64 = 0;
for &x in v {
if x % 2 == 0 { total += x * x; }
}
return total;
}
def indexed(v: &vector<u64>): u64 {
var total: u64 = 0;
for i in 0..v.length {
val x := v[i];
if x % 2 == 0 { total += x * x; }
}
return total;
}
def functors(v: &vector<u64>): u64 {
return v.iter().filter(is_even {}).map(square {}).sum();
}
def lambdas(v: &vector<u64>): u64 {
return v.iter().filter(def(x) => x % 2 == 0).map(def(x): u64 => x * x).sum();
}
def range_functors(n: u64): u64 {
return (0..n).filter(is_even_number {}).map(square_number {}).sum();
}
def range_lambdas(n: u64): u64 {
return (0..n).filter(def(x) => x % 2 == 0).map(def(x: u64): u64 => x * x).sum();
}
#! Runs a way ten times, writing how long it took and what it gave.
#! @param name What it is called.
#! @param run The way.
#! @returns How long it took, in nanoseconds.
def timed(name: strview, run: def(): u64): u64 {
val start := instant::now();
var sum: u64 = 0;
for _ in 0..10u {
sum += run();
}
val took := (instant::now() - start).in_nanoseconds as u64;
val ms := $"{took / 1000000}";
println($"{name.rpad(24, ' ')} {ms.lpad(6, ' ')} ms {sum}");
return took;
}
def main(args: span<strview>): void {
var n: u64 = 10000000;
if args.length > 0 {
n = integer::parse::<u64>(args[0]) else {
println("The count is a number, as 10000000.");
return;
};
}
var v := vector::<u64>::new();
v.reserve(n);
for i in 0..n {
v.append(i);
}
val r := &v;
timed("for x in 0..n", def(): u64 => counted(n));
val loop := timed("for &x in v", def(): u64 => referred(r));
timed("v[i]", def(): u64 => indexed(r));
val adapted := timed("adapters, functors", def(): u64 => functors(r));
timed("adapters, lambdas", def(): u64 => lambdas(r));
timed("range, functors", def(): u64 => range_functors(n));
timed("range, lambdas", def(): u64 => range_lambdas(n));
val ratio := adapted as f64 / (loop == 0 ? 1 : loop) as f64;
val verdict: strview = ratio <= 1.1 ? "within" : "outside";
println($"functors / for &x in v: {ratio}, {verdict} the measure of 1.1");
}
+148
View File
@@ -0,0 +1,148 @@
#! @file memory.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the probe of how fast a program's memory is, as `docs/performance.md`
#! records it: a list of 1,000,000 nodes built and summed, ten times over, its
#! nodes held each way std holds memory. Build it as an executable and run it on
#! one core:
#!
#! sakura build --lib std=../std -O2 -o memory tools/memory.sakura
#! taskset -c 2 ./memory
#!
#! A `box` should cost no more than a tenth more than `raw_allocate` does.
import std::allocators;
import std::io;
import std::time;
const nodes: u64 = 1000000;
const rounds: u64 = 10;
struct boxed {
var value: u64;
var next: maybe<box<boxed>>;
}
struct raw {
var value: u64;
var next: *mut raw;
}
# Nodes in a `box` each, owned by the node before, and taken out one by one from
# the front, since closing the first would close the rest within it, a frame each.
def with_boxes(): u64 {
var sum: u64 = 0;
for _ in 0..rounds {
var front: maybe<box<boxed>> = nothing {};
for i in 0..nodes {
front = box::<boxed>::new(boxed { value = i, next = move(&mut front) });
}
var at: maybe<&boxed> = nothing {};
if front is some(&first) {
at = first.get();
}
while at is some(&each) {
sum += each.value;
at = nothing {};
if each.next is some(&next) {
at = next.get();
}
}
while front is some(&mut first) {
var node := first.take();
front = move(&mut node.next);
}
}
return sum;
}
# Nodes `raw_allocate` gives, each released by itself.
def with_blocks(): u64 {
var sum: u64 = 0;
for _ in 0..rounds {
var front: *mut raw = null;
for i in 0..nodes {
val made := raw_allocate(size_of::<raw>()) as *mut raw;
made[0] = raw { value = i, next = front };
front = made;
}
var at := front;
while at != null {
sum += at[0].value;
at = at[0].next;
}
while front != null {
val next := front[0].next;
raw_release(front as *mut u8);
front = next;
}
}
return sum;
}
# Nodes of an arena, freed together as it resets.
def with_an_arena(): u64 {
var sum: u64 = 0;
var a := arena::new();
val alloc: maybe<&mut allocator> = &mut a;
for _ in 0..rounds {
var front: *mut raw = null;
for i in 0..nodes {
val made := acquire::<raw>(alloc, 1);
made[0] = raw { value = i, next = front };
front = made;
}
var at := front;
while at != null {
sum += at[0].value;
at = at[0].next;
}
a.reset();
}
return sum;
}
# Nodes of a pool, each given back by itself.
def with_a_pool(): u64 {
var sum: u64 = 0;
var p := pool::of::<raw>();
for _ in 0..rounds {
var front: *mut raw = null;
for i in 0..nodes {
front = p.make(raw { value = i, next = front });
}
var at := front;
while at != null {
sum += at[0].value;
at = at[0].next;
}
while front != null {
val next := front[0].next;
p.unmake(front);
front = next;
}
}
return sum;
}
# Runs a way of holding the nodes, printing how long it took.
def timed(name: strview, way: def(): u64): f64 {
val start := time::instant::now();
val sum := way();
val took := (time::instant::now() - start) / time::milliseconds(1);
if sum != rounds * nodes * (nodes - 1) / 2 {
println($"{name}: the sum is {sum}, which is wrong");
}
println($"{name}: {took} ms");
return took;
}
def main(): void {
val boxes := timed("box, released one by one", with_boxes);
val blocks := timed("raw_allocate and raw_release, one by one", with_blocks);
_ = timed("an arena, reset once each time", with_an_arena);
_ = timed("a pool, each given back by itself", with_a_pool);
println($"box / raw_allocate: {boxes / blocks}");
}
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]}')