Debian Codegraph @

tools/profile.py

raw
1 """
2 Script to profile the build of the test site with py-spy.
3
4 This can be called with `python tools/profile.py` and will profile the build of the test
5 site.
6 You can additionally configure the number of extra pages to add to the build with the
7 `-n` flag and the output file with the `-o` flag.
8
9 $ python tools/profile.py -n 100 -o profile.svg
10
11 If running within tox (recommended) this can be run with:
12
13 $ tox -e profile-docs -- -n 100 -o profile.svg
14
15 """
16
17 import argparse
18 import shutil as sh
19 import subprocess
20 import tempfile
21
22 from pathlib import Path
23 from textwrap import dedent
24
25
26 def profile_docs(output: str = "profile.svg", n_extra_pages: int = 50) -> None:
27 """Add a bunch of extra pages to the test site and profile the build with py-spy.
28
29 Args:
30 output (str): The output filename for generated chart, defaults to output.svg.
31 n_extra_pages (int): The number of extra pages to add to the build, defaults to
32 50.
33 """
34 # base path of the test site
35 base_site_path = Path("tests/sites/base")
36
37 with tempfile.TemporaryDirectory() as tmpdir:
38 # copy over the base test site to the temporary folder
39 target_path = Path(tmpdir) / base_site_path
40 sh.copytree(base_site_path, target_path)
41 print(f"Copied {base_site_path} to {target_path}")
42
43 # Add a bunch of extra files to increase the build length
44 index_file = target_path / "index.rst"
45 dummy_text = index_file.read_text()
46 dummy_text += dedent(
47 """
48 .. toctree::
49 :glob:
50
51 many/*
52 """
53 )
54 index_file.write_text(dummy_text)
55 many_files_path = target_path / "many"
56 try:
57 many_files_path.mkdir(parents=False)
58 except FileNotFoundError:
59 print(f"Could not create directory {many_files_path}")
60
61 # create a bunch of empty pages to slow the build
62 for page in range(n_extra_pages):
63 (many_files_path / f"{page}.rst").write_text("Test\n====\n\nbody\n")
64
65 # Output directory
66 output_site_path = target_path / "_build"
67
68 # Profile the build
69 print(f"Profiling build with {n_extra_pages} pages with py-spy...")
70
71 subprocess.run(
72 [
73 "py-spy",
74 "record",
75 "-o",
76 output,
77 "--",
78 "sphinx-build",
79 target_path,
80 f" {output_site_path}/_build",
81 ],
82 capture_output=True,
83 )
84
85 print("py-spy profiler output at this file:", output)
86
87
88 if __name__ == "__main__":
89 parser = argparse.ArgumentParser()
90
91 parser.add_argument(
92 "-o", "--output", type=str, help="Output filename, the default is profile.svg"
93 )
94 parser.add_argument(
95 "-n", "--n_pages", type=int, help="Number of extra pages to add to the build"
96 )
97
98 # Parse the arguments
99 args = parser.parse_args()
100 output_file = args.output if args.output else "profile.svg"
101 n_pages = args.n_pages if args.n_pages else 50
102
103 profile_docs(output=output_file, n_extra_pages=n_pages)