|
| 1 | +"""Compile mypy using mypyc and profile type checking using perf. |
| 2 | +
|
| 3 | +By default does a self check. |
| 4 | +
|
| 5 | +Notes: |
| 6 | + - Only Linux is supported for now (TODO: add support for other profilers) |
| 7 | + - The profile is collected at C level |
| 8 | + - It includes C functions compiled by mypyc and CPython runtime functions |
| 9 | + - The names of mypy functions are mangled to C names, but usually it's clear what they mean |
| 10 | + - Generally CPyDef_ prefix for native functions and CPyPy_ prefix for wrapper functions |
| 11 | + - It's important to compile CPython using special flags (see below) to get good results |
| 12 | + - Generally use the latest Python feature release (or the most recent beta if supported by mypyc) |
| 13 | + - The tool prints a command that can be used to analyze the profile afterwards |
| 14 | +
|
| 15 | +You may need to adjust kernel parameters temporarily, e.g. this (note that this has security |
| 16 | +implications): |
| 17 | +
|
| 18 | + sudo sysctl kernel.perf_event_paranoid=-1 |
| 19 | +
|
| 20 | +This is the recommended way to configure CPython for profiling: |
| 21 | +
|
| 22 | + ./configure \ |
| 23 | + --enable-optimizations \ |
| 24 | + --with-lto \ |
| 25 | + CFLAGS="-O2 -g -fno-omit-frame-pointer" |
| 26 | +""" |
| 27 | + |
| 28 | +from __future__ import annotations |
| 29 | + |
| 30 | +import argparse |
| 31 | +import glob |
| 32 | +import os |
| 33 | +import shutil |
| 34 | +import subprocess |
| 35 | +import sys |
| 36 | +import time |
| 37 | + |
| 38 | +from perf_compare import build_mypy, clone |
| 39 | + |
| 40 | +# Use these C compiler flags when compiling mypy (important). Note that it's strongly recommended |
| 41 | +# to also compile CPython using similar flags, but we don't enforce it in this script. |
| 42 | +CFLAGS = "-O2 -fno-omit-frame-pointer -g" |
| 43 | + |
| 44 | +# Generated files, including binaries, go under this directory to avoid overwriting user state. |
| 45 | +TARGET_DIR = "mypy.profile.tmpdir" |
| 46 | + |
| 47 | + |
| 48 | +def _profile_type_check(target_dir: str, code: str | None) -> None: |
| 49 | + cache_dir = os.path.join(target_dir, ".mypy_cache") |
| 50 | + if os.path.exists(cache_dir): |
| 51 | + shutil.rmtree(cache_dir) |
| 52 | + args = [] |
| 53 | + if code is None: |
| 54 | + args.extend(["--config-file", "mypy_self_check.ini"]) |
| 55 | + for pat in "mypy/*.py", "mypy/*/*.py", "mypyc/*.py", "mypyc/test/*.py": |
| 56 | + args.extend(glob.glob(pat)) |
| 57 | + else: |
| 58 | + args.extend(["-c", code]) |
| 59 | + check_cmd = ["python", "-m", "mypy"] + args |
| 60 | + cmdline = ["perf", "record", "-g"] + check_cmd |
| 61 | + t0 = time.time() |
| 62 | + subprocess.run(cmdline, cwd=target_dir, check=True) |
| 63 | + elapsed = time.time() - t0 |
| 64 | + print(f"{elapsed:.2f}s elapsed") |
| 65 | + |
| 66 | + |
| 67 | +def profile_type_check(target_dir: str, code: str | None) -> None: |
| 68 | + try: |
| 69 | + _profile_type_check(target_dir, code) |
| 70 | + except subprocess.CalledProcessError: |
| 71 | + print("\nProfiling failed! You may missing some permissions.") |
| 72 | + print("\nThis may help (note that it has security implications):") |
| 73 | + print(" sudo sysctl kernel.perf_event_paranoid=-1") |
| 74 | + sys.exit(1) |
| 75 | + |
| 76 | + |
| 77 | +def check_requirements() -> None: |
| 78 | + if sys.platform != "linux": |
| 79 | + # TODO: How to make this work on other platforms? |
| 80 | + sys.exit("error: Only Linux is supported") |
| 81 | + |
| 82 | + try: |
| 83 | + subprocess.run(["perf", "-h"], capture_output=True) |
| 84 | + except (subprocess.CalledProcessError, FileNotFoundError): |
| 85 | + print("error: The 'perf' profiler is not installed") |
| 86 | + sys.exit(1) |
| 87 | + |
| 88 | + try: |
| 89 | + subprocess.run(["clang", "--version"], capture_output=True) |
| 90 | + except (subprocess.CalledProcessError, FileNotFoundError): |
| 91 | + print("error: The clang compiler is not installed") |
| 92 | + sys.exit(1) |
| 93 | + |
| 94 | + if not os.path.isfile("mypy_self_check.ini"): |
| 95 | + print("error: Run this in the mypy repository root") |
| 96 | + sys.exit(1) |
| 97 | + |
| 98 | + |
| 99 | +def main() -> None: |
| 100 | + check_requirements() |
| 101 | + |
| 102 | + parser = argparse.ArgumentParser( |
| 103 | + description="Compile mypy and profile type checking using 'perf' (by default, self check)." |
| 104 | + ) |
| 105 | + parser.add_argument( |
| 106 | + "--multi-file", |
| 107 | + action="store_true", |
| 108 | + help="compile mypy into one C file per module (to reduce RAM use during compilation)", |
| 109 | + ) |
| 110 | + parser.add_argument( |
| 111 | + "--skip-compile", action="store_true", help="use compiled mypy from previous run" |
| 112 | + ) |
| 113 | + parser.add_argument( |
| 114 | + "-c", |
| 115 | + metavar="CODE", |
| 116 | + default=None, |
| 117 | + type=str, |
| 118 | + help="profile type checking Python code fragment instead of mypy self-check", |
| 119 | + ) |
| 120 | + args = parser.parse_args() |
| 121 | + multi_file: bool = args.multi_file |
| 122 | + skip_compile: bool = args.skip_compile |
| 123 | + code: str | None = args.c |
| 124 | + |
| 125 | + target_dir = TARGET_DIR |
| 126 | + |
| 127 | + if not skip_compile: |
| 128 | + clone(target_dir, "HEAD") |
| 129 | + |
| 130 | + print(f"Building mypy in {target_dir}...") |
| 131 | + build_mypy(target_dir, multi_file, cflags=CFLAGS) |
| 132 | + elif not os.path.isdir(target_dir): |
| 133 | + sys.exit("error: Can't find compile mypy from previous run -- can't use --skip-compile") |
| 134 | + |
| 135 | + profile_type_check(target_dir, code) |
| 136 | + |
| 137 | + print() |
| 138 | + print('NOTE: Compile CPython using CFLAGS="-O2 -g -fno-omit-frame-pointer" for good results') |
| 139 | + print() |
| 140 | + print("CPU profile collected. You can now analyze the profile:") |
| 141 | + print(f" perf report -i {target_dir}/perf.data ") |
| 142 | + |
| 143 | + |
| 144 | +if __name__ == "__main__": |
| 145 | + main() |
0 commit comments