Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions docs/performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,25 @@ most of its time is the Myers diff, which was not changed.

Run these numbers again with the shared benchmark (#47) once it is merged.

## Reproduction

The benchmark is checked in as `scripts/benchmark_working_tree.py`. It builds a throwaway repository with 3000 small files (40 lines each, in 50 folders) and one 20000-line file, commits them, and times one call of `cmd_status` and `cmd_diff` in each situation. From the repository root:

PYTHONPATH=. python3 scripts/benchmark_working_tree.py
PYTHONPATH=. python3 scripts/benchmark_working_tree.py --profile

Run on 2026-11-19 on `main` at `2e87586` plus the W10 branch changes (this script and the switch to `get_merge_status()`, which do not touch the file walk), Python 3.13.5, MacBook Air (Apple silicon). One run, no other heavy programs open:

| Situation | status | diff |
| --- | --- | --- |
| nothing changed | 0.072 s | 0.070 s |
| 1 small file changed | 0.071 s | 0.070 s |
| 50 small files changed | 0.071 s | 0.072 s |
| + big file, 2 edits | 0.071 s | 0.078 s |
| + big file, 500 scattered edits | 0.071 s | 0.177 s |

These agree with the After table above to within about 0.01 s, which is ordinary run-to-run variation. This is a Module 2 fixture, not the shared project benchmark in #47, which is not merged yet. Need to rerun with that still.

# Object-storage performance

## How it was measured
Expand Down
8 changes: 4 additions & 4 deletions minigit/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,11 +535,11 @@ def cmd_add(args) -> int:
full_path = os.path.join(wt.root, args.path)
rel_path = os.path.relpath(full_path, wt.root).replace(os.sep, "/")
wt._validate_checkout_path(rel_path)
pending = manager._read_pending_merge()
merge = manager.get_merge_status()
# A delete/modify conflict can have no pre-merge index entry. Explicitly
# adding its absent path still resolves the conflict as a deletion.
missing_conflict = (
pending is not None and rel_path in pending[3] and not os.path.lexists(full_path)
merge is not None and rel_path in merge.unresolved_paths and not os.path.lexists(full_path)
)
if missing_conflict:
wt.write_index([entry for entry in wt.read_index() if entry.path != rel_path])
Expand Down Expand Up @@ -602,8 +602,8 @@ def _head_header(head) -> str:

def _unresolved_merge_paths(manager) -> list[str]:
"""Paths of a pending merge that `add` has not resolved yet (M3 owns the merge state)."""
pending = manager._read_pending_merge()
return sorted(pending[3]) if pending else []
merge = manager.get_merge_status()
return sorted(merge.unresolved_paths) if merge else []


def cmd_status(args) -> int:
Expand Down
128 changes: 128 additions & 0 deletions scripts/benchmark_working_tree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
"""Time `minigit status` and `minigit diff` on a generated repository. Not part of CI.

Run from the repository root with the project's virtual environment active, or with
PYTHONPATH=. set:

python3 scripts/benchmark_working_tree.py # timings
python3 scripts/benchmark_working_tree.py --profile # timings + where the time goes

It builds a throwaway repository in a temporary folder, so it never touches your own work.
"""

import argparse
import contextlib
import cProfile
import io
import os
import pstats
import random
import tempfile
import time

from minigit.commits import CommitManager
from minigit.index import IndexEntry, WorkingTree, cmd_diff, cmd_status

SMALL_FILES = 3000
BIG_FILE_LINES = 20000


def build_repo(root):
"""3000 small files and one big file, all committed."""
os.chdir(root)
os.makedirs(".minigit")
for i in range(SMALL_FILES):
folder = f"d{i % 50}"
os.makedirs(folder, exist_ok=True)
with open(f"{folder}/f{i}.txt", "w") as f:
f.write("".join(f"line {j} of {i}\n" for j in range(40)))
random.seed(1)
with open("big.txt", "w") as f:
f.write("".join(f"big line {j} {random.randint(0, 50)}\n" for j in range(BIG_FILE_LINES)))

tree = WorkingTree()
entries = []
for folder, dirs, files in os.walk("."):
dirs[:] = [d for d in dirs if d != ".minigit"]
for name in files:
path = os.path.relpath(os.path.join(folder, name), ".").replace(os.sep, "/")
with open(path, "rb") as f:
blob = tree.store.write_object(f.read(), "blob")
entries.append(IndexEntry("100644", blob, path))
tree.write_index(entries) # faster than 3000 `add` calls, which is not what we measure
CommitManager().create_commit(tree.build_tree_from_index(), [], "bench", "first")


def edit_small_files(count):
for i in range(count):
with open(f"d{i % 50}/f{i}.txt", "a") as f:
f.write("edit\n")


def edit_big_file(every):
with open("big.txt") as f:
lines = f.readlines()
for k in range(0, len(lines), every):
lines[k] = f"changed {k}\n"
with open("big.txt", "w") as f:
f.writelines(lines)


def run(command, profile=False, repeat=5):
"""Best of `repeat` runs, in seconds. Output is thrown away."""
best = None
stats = None
for _ in range(repeat):
with contextlib.redirect_stdout(io.StringIO()):
profiler = cProfile.Profile() if profile else None
start = time.perf_counter()
if profiler:
profiler.enable()
command(None)
if profiler:
profiler.disable()
elapsed = time.perf_counter() - start
if best is None or elapsed < best:
best, stats = elapsed, profiler
return best, stats


def show_profile(label, profiler):
out = io.StringIO()
pstats.Stats(profiler, stream=out).strip_dirs().sort_stats("tottime").print_stats(6)
print(f"\n--- where the time goes: {label} (sorted by time spent inside each function) ---")
for line in out.getvalue().splitlines():
if line.strip() and "Ordered by" not in line:
print(line[:120])


def main():
parser = argparse.ArgumentParser()
parser.add_argument("--profile", action="store_true", help="also show the slowest functions")
args = parser.parse_args()

with tempfile.TemporaryDirectory() as root:
build_repo(root)
print(f"repo: {SMALL_FILES} small files + one {BIG_FILE_LINES}-line file\n")
print(f"{'situation':44s} {'status':>9s} {'diff':>9s}")

def row(label):
status_time, status_prof = run(cmd_status, args.profile)
diff_time, diff_prof = run(cmd_diff, args.profile)
print(f"{label:44s} {status_time:8.3f}s {diff_time:8.3f}s")
if args.profile:
show_profile(f"status, {label}", status_prof)
show_profile(f"diff, {label}", diff_prof)

row("nothing changed")
edit_small_files(1)
row("1 small file changed")
edit_small_files(50)
row("50 small files changed")
edit_big_file(every=10000)
row("+ big file, 2 edits")
edit_big_file(every=40)
row("+ big file, 500 scattered edits")


if __name__ == "__main__":
main()
6 changes: 3 additions & 3 deletions tests/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,7 @@ def get_head_tree(self):
def read_head(self):
return None

def _read_pending_merge(self):
def get_merge_status(self):
return None

fake = types.ModuleType("minigit.commits")
Expand Down Expand Up @@ -1363,8 +1363,8 @@ def test_status_lists_unresolved_merge_paths_from_the_manager(cli_repo, capsys,
write(repo, "a.txt", "x\n")
monkeypatch.setattr(
sys.modules["minigit.commits"].CommitManager,
"_read_pending_merge",
lambda self: ("ours", "theirs", "merge", ["a.txt"]),
"get_merge_status",
lambda self: types.SimpleNamespace(unresolved_paths=("a.txt",)),
)

# one heading, no duplicates: a.txt is not also "untracked" or "not staged"
Expand Down
Loading