Repository navigation
bench: track binding FFI overhead nightly against Rust baselines #5607
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
ec4803a
quest: claim m1/ffi-bench
kixelated 378e8f3
bench: track binding FFI overhead nightly against Rust baselines
kixelated fcb778d
quest: plan Kotlin binding call overhead from the first numbers
kixelated c4a23f3
bench: check payload bytes in every runner, run Rust through nextest
kixelated 7045edf
Merge remote-tracking branch 'origin/main' into quest/m1/ffi-bench
kixelated 55cf294
bench: bound every runner's cache and close Kotlin handles per case
kixelated 404c00a
bench: guard each Rust round against a wedge, build the payload once …
kixelated 186a571
bench: bound each Python and Kotlin round against a lost wakeup
kixelated 6a2f93b
Merge remote-tracking branch 'origin/main' into quest/m1/ffi-bench
kixelated File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| #!/usr/bin/env python3 | ||
| """Combine the binding benchmark's per-runner results into one table and report. | ||
|
|
||
| Each runner writes `<dir>/<runner>.json`, a list of {name, unit, value}. The table shows | ||
| every runner beside its ratio to the `rust-ffi` baseline, run on the same machine, which | ||
| cancels most of the runner's own speed. `report.json` holds every value and ratio, named | ||
| `<runner>/<name>`, for the trend history. | ||
| """ | ||
| import argparse | ||
| import json | ||
| import os | ||
| from pathlib import Path | ||
|
|
||
| BASELINE = 'rust-ffi' | ||
| # Baselines first, then the wrappers in a stable order. | ||
| ORDER = ('rust-net', 'rust-ffi') | ||
| SMALLER_IS_BETTER = {'ms/MB', 'ns'} | ||
|
|
||
|
|
||
| def load(directory): | ||
| runners = {} | ||
| for path in sorted(Path(directory).glob('*.json')): | ||
| if path.name == 'report.json': | ||
| continue | ||
| runners[path.stem] = {entry['name']: entry for entry in json.loads(path.read_text())} | ||
| if BASELINE not in runners: | ||
| raise ValueError(f'missing the {BASELINE} baseline in {directory}') | ||
| return runners | ||
|
|
||
|
|
||
| def order(runners): | ||
| return sorted(runners, key=lambda r: (ORDER.index(r) if r in ORDER else len(ORDER), r)) | ||
|
|
||
|
|
||
| def ratio(entry, baseline): | ||
| """How many times worse than the baseline: above 1 is slower or costlier.""" | ||
| if baseline is None or not baseline['value'] or not entry['value']: | ||
| return None | ||
| if entry['unit'] in SMALLER_IS_BETTER: | ||
| return entry['value'] / baseline['value'] | ||
| return baseline['value'] / entry['value'] | ||
|
|
||
|
|
||
| def report(runners): | ||
| entries = [] | ||
| baseline = runners[BASELINE] | ||
| for runner in order(runners): | ||
| for name, entry in runners[runner].items(): | ||
| entries.append({'name': f'{runner}/{name}', 'unit': entry['unit'], 'value': entry['value']}) | ||
| if runner != BASELINE and (r := ratio(entry, baseline.get(name))) is not None: | ||
| entries.append({'name': f'{runner}/{name} vs {BASELINE}', 'unit': 'x', 'value': r}) | ||
| return entries | ||
|
|
||
|
|
||
| def table(runners): | ||
| columns = order(runners) | ||
| names = list(dict.fromkeys(name for runner in columns for name in runners[runner])) | ||
| baseline = runners[BASELINE] | ||
| lines = [ | ||
| '| benchmark | unit | ' + ' | '.join(columns) + ' |', | ||
| '|---|---|' + '---|' * len(columns), | ||
| ] | ||
| for name in names: | ||
| unit = next(runners[r][name]['unit'] for r in columns if name in runners[r]) | ||
| cells = [] | ||
| for runner in columns: | ||
| entry = runners[runner].get(name) | ||
| if entry is None: | ||
| cells.append('') | ||
| continue | ||
| cell = f"{entry['value']:.4g}" | ||
| if runner != BASELINE and (r := ratio(entry, baseline.get(name))) is not None: | ||
| cell += f' ({r:.2f}x)' | ||
| cells.append(cell) | ||
| lines.append(f'| {name} | {unit} | ' + ' | '.join(cells) + ' |') | ||
| return '\n'.join(lines) | ||
|
|
||
|
|
||
| def main(): | ||
| parser = argparse.ArgumentParser(description=__doc__) | ||
| parser.add_argument('directory') | ||
| args = parser.parse_args() | ||
| runners = load(args.directory) | ||
| (Path(args.directory) / 'report.json').write_text(json.dumps(report(runners), indent=2)) | ||
| markdown = ( | ||
| f'## Binding benchmark\n\nRatios are against `{BASELINE}`; above 1x is slower or costlier.\n\n' | ||
| + table(runners) | ||
| + '\n' | ||
| ) | ||
| print(markdown) | ||
| if summary := os.environ.get('GITHUB_STEP_SUMMARY'): | ||
| with open(summary, 'a') as f: | ||
| f.write(markdown) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| #!/usr/bin/env bash | ||
| # Run the binding benchmark: the Rust baselines and every wrapper's runner on this | ||
| # machine, then the ratio table. Ratios only hold within one machine, so stale | ||
| # results from an earlier run are cleared first. | ||
| set -euo pipefail | ||
| root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) | ||
| export MOQ_BENCH_DIR="${MOQ_BENCH_DIR:-$root/target/bench/ffi}" | ||
| rm -rf "$MOQ_BENCH_DIR" | ||
|
|
||
| cd "$root" | ||
| # Through nextest like every Rust test; each round guards itself against a wedged read. | ||
| just rs test -p moq-ffi --cargo-profile release -E 'test(bench::benchmark_ffi)' --run-ignored only | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| just go bench -benchtime="${MOQ_BENCH_SECONDS:-1}s" | ||
| just py bench | ||
| just kt bench | ||
| python3 bench/ffi.py "$MOQ_BENCH_DIR" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| #!/usr/bin/env python3 | ||
| import importlib.util | ||
| import json | ||
| import tempfile | ||
| import unittest | ||
| from pathlib import Path | ||
|
|
||
| spec = importlib.util.spec_from_file_location('ffi', Path(__file__).with_name('ffi.py')) | ||
| ffi = importlib.util.module_from_spec(spec) | ||
| spec.loader.exec_module(ffi) | ||
|
|
||
|
|
||
| def write(directory, runner, entries): | ||
| (Path(directory) / f'{runner}.json').write_text( | ||
| json.dumps([{'name': n, 'unit': u, 'value': v} for n, u, v in entries]) | ||
| ) | ||
|
|
||
|
|
||
| class FfiTest(unittest.TestCase): | ||
| def runners(self, directory): | ||
| write(directory, 'rust-ffi', [('throughput/a', 'MB/s', 100.0), ('cpu/a', 'ms/MB', 2.0)]) | ||
| write(directory, 'rust-net', [('throughput/a', 'MB/s', 200.0)]) | ||
| write(directory, 'python', [('throughput/a', 'MB/s', 25.0), ('cpu/a', 'ms/MB', 8.0)]) | ||
| return ffi.load(directory) | ||
|
|
||
| def test_ratio_is_worse_above_one(self): | ||
| with tempfile.TemporaryDirectory() as directory: | ||
| report = {e['name']: e['value'] for e in ffi.report(self.runners(directory))} | ||
| self.assertEqual(report['python/throughput/a vs rust-ffi'], 4.0) | ||
| self.assertEqual(report['python/cpu/a vs rust-ffi'], 4.0) | ||
| self.assertEqual(report['rust-net/throughput/a vs rust-ffi'], 0.5) | ||
| self.assertNotIn('rust-ffi/throughput/a vs rust-ffi', report) | ||
|
|
||
| def test_table_orders_baselines_first(self): | ||
| with tempfile.TemporaryDirectory() as directory: | ||
| table = ffi.table(self.runners(directory)) | ||
| self.assertTrue(table.splitlines()[0].startswith('| benchmark | unit | rust-net | rust-ffi | python |')) | ||
| self.assertIn('| throughput/a | MB/s | 200 (0.50x) | 100 | 25 (4.00x) |', table) | ||
|
|
||
| def test_missing_baseline_fails(self): | ||
| with tempfile.TemporaryDirectory() as directory: | ||
| write(directory, 'python', [('throughput/a', 'MB/s', 25.0)]) | ||
| with self.assertRaises(ValueError): | ||
| ffi.load(directory) | ||
|
|
||
| def test_skips_its_own_report(self): | ||
| with tempfile.TemporaryDirectory() as directory: | ||
| self.runners(directory) | ||
| (Path(directory) / 'report.json').write_text('[]') | ||
| self.assertNotIn('report', ffi.load(directory)) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| unittest.main() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.