|
| 1 | +# This file is a part of sqliteimport <https://github.com/kurtmckee/sqliteimport> |
| 2 | +# Copyright 2024-2025 Kurt McKee <[email protected]> |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +import itertools |
| 6 | +import json |
| 7 | +import pathlib |
| 8 | +import typing |
| 9 | + |
| 10 | +import click |
| 11 | + |
| 12 | +from . import LOG_PATHS |
| 13 | +from . import PACKAGE_PATHS |
| 14 | +from . import STATS |
| 15 | +from . import CodeType |
| 16 | +from . import Importer |
| 17 | +from . import Measurement |
| 18 | + |
| 19 | + |
| 20 | +@click.command() |
| 21 | +def collect() -> None: |
| 22 | + """ |
| 23 | + Collect import and sizing stats and write them to a JSON file. |
| 24 | + """ |
| 25 | + |
| 26 | + stats = { |
| 27 | + Measurement.time: parse_import_log(), |
| 28 | + Measurement.size: get_size_stats(), |
| 29 | + } |
| 30 | + output_path = STATS / "stats.json" |
| 31 | + output_path.parent.mkdir(exist_ok=True) |
| 32 | + output_path.write_text(json.dumps(stats, indent=2, sort_keys=True)) |
| 33 | + |
| 34 | + |
| 35 | +def parse_import_log() -> dict[str, dict[str, dict[str, int]]]: |
| 36 | + """Parse an import log to extract per-module cumulative import times (in µs).""" |
| 37 | + |
| 38 | + stats: dict[str, dict[str, dict[str, int]]] = {} |
| 39 | + for importer, code_type in itertools.product(Importer, CodeType): |
| 40 | + stats.setdefault(code_type, {})[importer] = {"-cumulative_us": 0} |
| 41 | + file = LOG_PATHS[importer][code_type] |
| 42 | + if not file.is_file(): |
| 43 | + click.echo(f"{file} not found") |
| 44 | + continue |
| 45 | + |
| 46 | + content = file.read_text() |
| 47 | + |
| 48 | + for _, cumulative_us, module in split_columns(content): |
| 49 | + if module.startswith(" "): |
| 50 | + # The module is an indented submodule. |
| 51 | + # Only top-level modules are recorded here. |
| 52 | + continue |
| 53 | + stats[code_type][importer][module] = cumulative_us |
| 54 | + stats[code_type][importer]["-cumulative_us"] += cumulative_us |
| 55 | + |
| 56 | + return stats |
| 57 | + |
| 58 | + |
| 59 | +def split_columns(text: str) -> typing.Iterator[tuple[int, int, str]]: |
| 60 | + for line in text.splitlines(): |
| 61 | + prefix, _, remainder = line.partition(": ") |
| 62 | + if prefix != "import time": |
| 63 | + continue |
| 64 | + try: |
| 65 | + self, cumulative, module = remainder.split(" | ") |
| 66 | + yield int(self.strip()), int(cumulative.strip()), module.rstrip() |
| 67 | + except (TypeError, ValueError): |
| 68 | + continue |
| 69 | + |
| 70 | + |
| 71 | +def get_size_stats() -> dict[Importer, dict[CodeType, int]]: |
| 72 | + """Get the size of items on disk. |
| 73 | +
|
| 74 | + This only considers the raw sum of the sizes of files on disk. |
| 75 | + It does not, for example, calculate the size of the filesystem blocks |
| 76 | + that are consumed by individual files. |
| 77 | + """ |
| 78 | + |
| 79 | + importer: Importer |
| 80 | + code_type: CodeType |
| 81 | + |
| 82 | + sizes: dict[Importer, dict[CodeType, int]] = { |
| 83 | + importer: {code_type: -1 for code_type in CodeType} for importer in Importer |
| 84 | + } |
| 85 | + for importer, code_type in itertools.product(Importer, CodeType): |
| 86 | + path = PACKAGE_PATHS[importer][code_type] |
| 87 | + if path.is_dir(): |
| 88 | + sizes[importer][code_type] = get_directory_size(path, code_type) |
| 89 | + elif path.is_file(): |
| 90 | + sizes[importer][code_type] = path.stat().st_size |
| 91 | + else: |
| 92 | + typing.assert_never((importer, code_type)) |
| 93 | + |
| 94 | + return sizes |
| 95 | + |
| 96 | + |
| 97 | +def get_directory_size(directory: pathlib.Path, code_type: CodeType) -> int: |
| 98 | + """Get the size of a directory. |
| 99 | +
|
| 100 | + PEP3147-compatible ``*.pyc`` files will be included in the calculation |
| 101 | + if the *code_type* indicates byte code. |
| 102 | + """ |
| 103 | + |
| 104 | + size = 0 |
| 105 | + |
| 106 | + directories = [directory] |
| 107 | + while directories: |
| 108 | + directory = directories.pop() |
| 109 | + for path in directory.glob("*"): |
| 110 | + if path.is_dir(): |
| 111 | + # Skip `__pycache__/` directories unless calculating byte code size. |
| 112 | + if path.name == "__pycache__" and code_type != CodeType.bytecode: |
| 113 | + continue |
| 114 | + directories.append(path) |
| 115 | + |
| 116 | + elif path.is_file(): |
| 117 | + # Skip `*.pyc` files unless calculating byte code size. |
| 118 | + # Even then, the `*.pyc` files must be in a `__pycache__/` directory. |
| 119 | + if path.suffix == ".pyc": |
| 120 | + if not ( |
| 121 | + code_type == CodeType.bytecode |
| 122 | + and path.parent.name == "__pycache__" |
| 123 | + ): |
| 124 | + continue |
| 125 | + |
| 126 | + size += path.stat().st_size |
| 127 | + |
| 128 | + return size |
0 commit comments