-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyze_profiles.py
More file actions
82 lines (68 loc) · 2.35 KB
/
analyze_profiles.py
File metadata and controls
82 lines (68 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File: analyze_profiles.py
import logging
import pstats
from pathlib import Path
from pstats import SortKey
from typing import Annotated
import typer
# Configure logging for the script itself
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logger = logging.getLogger(__name__)
app = typer.Typer(
help="Analyzes cProfile output files (.prof) generated by AlphaTriangle workers."
)
# Define annotations for Typer arguments/options
ProfilePathArg = Annotated[
Path,
typer.Argument(
..., # Ellipsis makes it a required argument
help="Path to the .prof file to analyze.",
exists=True,
file_okay=True,
dir_okay=False,
readable=True,
resolve_path=True,
),
]
# --- Corrected Option Definition (Default in Function Signature) ---
# Remove default from Option(), add it to the function parameter below
NumLinesOption = Annotated[
int,
typer.Option("--lines", "-n", help="Number of lines to show."),
]
# --- End Correction ---
@app.command()
def analyze(
profile_path: ProfilePathArg, # Use the annotation
num_lines: NumLinesOption = 30, # Assign default value here
):
"""
Loads a .prof file and prints statistics sorted by cumulative and total time.
"""
logger.info(f"Analyzing profile: {profile_path}")
try:
# Ensure profile_path is converted to string for pstats
p = pstats.Stats(str(profile_path))
except Exception as e:
logger.error(f"Error loading profile stats from {profile_path}: {e}")
# Add 'from e' to preserve original exception context
raise typer.Exit(code=1) from e
# Remove directory paths for cleaner output
p.strip_dirs()
print("\n" + "=" * 30)
print(f" Top {num_lines} Functions by Cumulative Time")
print("=" * 30)
try:
p.sort_stats(SortKey.CUMULATIVE).print_stats(num_lines)
except Exception as e:
logger.error(f"Error sorting/printing by cumulative time: {e}")
print("\n" + "=" * 30)
print(f" Top {num_lines} Functions by Total Internal Time")
print("=" * 30)
try:
p.sort_stats(SortKey.TIME).print_stats(num_lines) # SortKey.TIME is Tottime
except Exception as e:
logger.error(f"Error sorting/printing by total time: {e}")
logger.info(f"Finished analyzing {profile_path}")
if __name__ == "__main__":
app()