Claude Code for pstats: Python Profile Statistics Analysis — Claude Skills 360 Blog
Blog / AI / Claude Code for pstats: Python Profile Statistics Analysis
AI

Claude Code for pstats: Python Profile Statistics Analysis

Published: October 4, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s pstats module loads and analyzes profiling data produced by cProfile or profile. import pstats. Stats: s = pstats.Stats("output.prof") — load from file; or pstats.Stats(cprofile_obj) from a running profile. sort_stats: s.sort_stats("cumulative") — sort by cumulative time; "tottime" (self time), "ncalls", "pcalls" (primitive calls), "filename", "name". pstats.SortKey.CUMULATIVE enum (3.7+). print_stats: s.print_stats(10) — top 10 lines; s.print_stats("mymodule") — filter by regex; s.print_stats(0.1) — top 10% of entries. print_callers: s.print_callers(10) — show which functions called each entry. print_callees: s.print_callees(10) — show what each function called. strip_dirs: s.strip_dirs() — remove path prefixes from filenames. add: s.add("second_run.prof") — merge multiple profiles. dump_stats: s.dump_stats("output.prof") — save back to file. get_stats_profile: sp = s.get_stats_profile() (3.12+) → StatsProfile(total_tt, func_profiles). Each function entry: (ncalls, tottime, percall_tottime, cumtime, percall_cumtime, file:line(name)). stdout: stream = io.StringIO(); pstats.Stats(prof, stream=stream) — capture output. Claude Code generates profiling harnesses, flamegraph preparers, hotspot reporters, and CI regression detectors.

CLAUDE.md for pstats

## pstats Stack
- Stdlib: import cProfile, pstats, io
- Run:    prof = cProfile.Profile(); prof.enable(); ...; prof.disable()
- Save:   prof.dump_stats("out.prof")
- Load:   s = pstats.Stats("out.prof", stream=io.StringIO())
- Sort:   s.sort_stats("cumulative").print_stats(20)
- Merge:  s.add("run2.prof")
- Capture: buf=io.StringIO(); pstats.Stats(prof, stream=buf).sort_stats("cumtime").print_stats(10)

pstats Profile Analysis Pipeline

# app/pstatsutil.py — run, load, sort, report, compare, top functions
from __future__ import annotations

import cProfile
import io
import os
import pstats
import time
from contextlib import contextmanager
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Generator


# ─────────────────────────────────────────────────────────────────────────────
# 1. Profile collection helpers
# ─────────────────────────────────────────────────────────────────────────────

@contextmanager
def profile(
    output: str | Path | None = None,
    clock: str = "process_time",
) -> Generator[cProfile.Profile, None, None]:
    """
    Context manager that profiles the enclosed block and yields the Profile.
    Optionally saves to output path.

    Example:
        with profile("run.prof") as prof:
            my_expensive_function()
        report(prof, top=10)
    """
    p = cProfile.Profile()
    p.enable()
    try:
        yield p
    finally:
        p.disable()
        if output:
            p.dump_stats(str(output))


def profile_function(
    fn: Callable,
    *args: Any,
    output: str | Path | None = None,
    **kwargs: Any,
) -> tuple[Any, cProfile.Profile]:
    """
    Profile a single function call and return (result, profile).

    Example:
        result, prof = profile_function(sorted, large_list, reverse=True)
        report(prof, top=5)
    """
    p = cProfile.Profile()
    p.enable()
    result = fn(*args, **kwargs)
    p.disable()
    if output:
        p.dump_stats(str(output))
    return result, p


# ─────────────────────────────────────────────────────────────────────────────
# 2. Stats loading and sorting
# ─────────────────────────────────────────────────────────────────────────────

def load_stats(
    source: str | Path | cProfile.Profile,
    strip_dirs: bool = True,
) -> pstats.Stats:
    """
    Load profiling stats from a .prof file or a cProfile.Profile object.

    Example:
        s = load_stats("run.prof")
        s.sort_stats("cumulative").print_stats(10)
    """
    buf = io.StringIO()
    s = pstats.Stats(str(source) if isinstance(source, Path) else source, stream=buf)
    if strip_dirs:
        s.strip_dirs()
    return s


def merge_stats(
    sources: list[str | Path | cProfile.Profile],
    strip_dirs: bool = True,
) -> pstats.Stats:
    """
    Merge multiple profile runs into a single Stats object.

    Example:
        combined = merge_stats(["run1.prof", "run2.prof", "run3.prof"])
        report_stats(combined)
    """
    if not sources:
        raise ValueError("sources must be non-empty")
    s = load_stats(sources[0], strip_dirs=strip_dirs)
    for src in sources[1:]:
        extra = pstats.Stats(str(src) if isinstance(src, Path) else src, stream=io.StringIO())
        if strip_dirs:
            extra.strip_dirs()
        s.add(extra)
    return s


# ─────────────────────────────────────────────────────────────────────────────
# 3. Report generation
# ─────────────────────────────────────────────────────────────────────────────

def report(
    source: str | Path | cProfile.Profile | pstats.Stats,
    top: int = 20,
    sort: str = "cumulative",
    filter_regex: str | None = None,
    callers: bool = False,
    callees: bool = False,
) -> str:
    """
    Generate a text profiling report and return it as a string.

    sort: "cumulative", "tottime", "ncalls", "pcalls", "filename".
    filter_regex: limit to matching function paths.

    Example:
        with profile() as prof:
            run_app()
        print(report(prof, top=15, sort="cumulative"))
    """
    buf = io.StringIO()
    if isinstance(source, pstats.Stats):
        s = source
        s.stream = buf
    else:
        s = pstats.Stats(
            str(source) if isinstance(source, Path) else source,
            stream=buf
        )
        s.strip_dirs()

    s.sort_stats(sort)
    if filter_regex:
        s.print_stats(top, filter_regex)
    else:
        s.print_stats(top)

    if callers:
        s.print_callers(top)
    if callees:
        s.print_callees(top)

    return buf.getvalue()


# ─────────────────────────────────────────────────────────────────────────────
# 4. Structured hotspot extraction
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class FunctionProfile:
    name:           str
    file:           str
    line:           int
    ncalls:         int
    tottime:        float    # self time (no sub-calls)
    cumtime:        float    # cumulative time (incl. sub-calls)
    tottime_per:    float    # tottime per call
    cumtime_per:    float    # cumtime per call

    def __str__(self) -> str:
        return (
            f"{self.cumtime:8.4f}s cum  "
            f"{self.tottime:8.4f}s tot  "
            f"{self.ncalls:6d} calls  "
            f"{self.name} ({self.file}:{self.line})"
        )


def top_functions(
    source: str | Path | cProfile.Profile,
    top: int = 20,
    sort: str = "cumulative",
    min_tottime: float = 0.0,
) -> list[FunctionProfile]:
    """
    Return the top hotspot functions as a structured list.

    Example:
        with profile() as prof:
            run_app()
        for fn in top_functions(prof, top=10):
            print(fn)
    """
    buf = io.StringIO()
    s = pstats.Stats(
        str(source) if isinstance(source, Path) else source,
        stream=buf
    )
    s.strip_dirs().sort_stats(sort)

    results: list[FunctionProfile] = []
    # pstats stores data as {(file, line, name): (cc, nc, tt, ct, callers)}
    for (file, line, name), (cc, nc, tt, ct, _callers) in s.stats.items():
        if tt < min_tottime:
            continue
        tot_per = tt / nc if nc else 0.0
        cum_per = ct / nc if nc else 0.0
        results.append(FunctionProfile(
            name=name, file=file, line=line, ncalls=nc,
            tottime=tt, cumtime=ct,
            tottime_per=tot_per, cumtime_per=cum_per,
        ))

    keys = {
        "cumulative": lambda f: -f.cumtime,
        "tottime":    lambda f: -f.tottime,
        "ncalls":     lambda f: -f.ncalls,
    }
    results.sort(key=keys.get(sort, keys["cumulative"]))
    return results[:top]


# ─────────────────────────────────────────────────────────────────────────────
# 5. Regression detection
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class ProfileDiff:
    name:         str
    baseline_cum: float
    current_cum:  float
    delta_s:      float
    pct_change:   float

    @property
    def is_regression(self) -> bool:
        return self.pct_change > 0

    def __str__(self) -> str:
        sign = "+" if self.delta_s >= 0 else ""
        return (f"  {self.name:40s}  "
                f"base={self.baseline_cum:.4f}s  "
                f"now={self.current_cum:.4f}s  "
                f"{sign}{self.delta_s:.4f}s ({sign}{self.pct_change:.1f}%)")


def compare_profiles(
    baseline: str | Path | cProfile.Profile,
    current:  str | Path | cProfile.Profile,
    top: int = 20,
    threshold_pct: float = 10.0,
) -> list[ProfileDiff]:
    """
    Compare two profiles and flag functions that regressed by more than threshold_pct.
    Returns regressions sorted by absolute delta (worst first).

    Example:
        regressions = compare_profiles("baseline.prof", "current.prof", threshold_pct=5)
        for d in regressions:
            print(d)
    """
    def _load(src) -> dict[str, float]:
        s = pstats.Stats(
            str(src) if isinstance(src, Path) else src,
            stream=io.StringIO()
        )
        s.strip_dirs()
        return {
            f"{file}:{line}({name})": ct
            for (file, line, name), (cc, nc, tt, ct, _) in s.stats.items()
        }

    base_map = _load(baseline)
    curr_map = _load(current)

    diffs: list[ProfileDiff] = []
    all_keys = set(base_map) | set(curr_map)
    for key in all_keys:
        b = base_map.get(key, 0.0)
        c = curr_map.get(key, 0.0)
        delta = c - b
        pct = (delta / b * 100) if b else (100.0 if c else 0.0)
        if abs(pct) >= threshold_pct:
            diffs.append(ProfileDiff(
                name=key, baseline_cum=b, current_cum=c,
                delta_s=delta, pct_change=pct,
            ))

    diffs.sort(key=lambda d: -abs(d.delta_s))
    return diffs[:top]


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import tempfile

    print("=== pstats demo ===")

    # ── workload to profile ────────────────────────────────────────────────────
    def _sort_heavy() -> list:
        data = list(range(5000, 0, -1))
        for _ in range(50):
            sorted(data)
        return data

    def _sum_heavy() -> int:
        total = 0
        for i in range(200_000):
            total += i
        return total

    def _workload() -> None:
        _sort_heavy()
        _sum_heavy()

    # ── profile_function ───────────────────────────────────────────────────────
    print("\n--- profile_function ---")
    with tempfile.TemporaryDirectory() as tmpdir:
        prof_path = Path(tmpdir) / "run.prof"

        result, prof = profile_function(_workload, output=prof_path)
        print(f"  profile saved: {prof_path.stat().st_size:,d} bytes")

        # ── report ─────────────────────────────────────────────────────────────
        print("\n--- report (top 8 cumulative) ---")
        txt = report(prof, top=8, sort="cumulative")
        for line in txt.splitlines()[:16]:
            print(f"  {line}")

        # ── top_functions ──────────────────────────────────────────────────────
        print("\n--- top_functions ---")
        fns = top_functions(prof_path, top=5, sort="tottime")
        for fn in fns:
            print(f"  {fn}")

        # ── merge_stats ────────────────────────────────────────────────────────
        print("\n--- merge_stats ---")
        prof_path2 = Path(tmpdir) / "run2.prof"
        _, prof2 = profile_function(_workload, output=prof_path2)
        combined = merge_stats([prof_path, prof_path2])
        merged_fns = top_functions(combined, top=3)
        print(f"  merged top 3:")
        for fn in merged_fns:
            print(f"    {fn}")

        # ── compare_profiles ───────────────────────────────────────────────────
        print("\n--- compare_profiles ---")
        diffs = compare_profiles(prof_path, prof_path2, threshold_pct=5.0)
        print(f"  {len(diffs)} functions changed > 5% (noise expected across runs)")

        # ── context manager ────────────────────────────────────────────────────
        print("\n--- profile context manager ---")
        with profile(Path(tmpdir) / "ctx.prof") as p:
            _sort_heavy()
        txt2 = report(p, top=3, sort="cumulative")
        print(f"  captured {len(txt2.splitlines())} lines of output")

    print("\n=== done ===")

For the cProfile alternative — cProfile is the standard deterministic profiler that produces the data that pstats analyzes; running python -m cProfile -o out.prof script.py or using cProfile.Profile() programmatically and then passing the result to pstats.Stats() is the canonical profiling workflow — cProfile collects the data and pstats analyzes it; use pstats whenever you need to load, sort, filter, or compare .prof files rather than doing interactive analysis. For the pyinstrument / scalene alternative — pyinstrument (PyPI) uses statistical sampling rather than deterministic instrumentation, which adds far less overhead (1-10% vs. up to 100× for cProfile) and produces flame-graph output; scalene (PyPI) profiles CPU, GPU, and memory simultaneously with line-level granularity — use pyinstrument or scalene when profiling production or near-production workloads where deterministic profiling overhead is unacceptable; use cProfile+pstats for detailed call-count and exact timing analysis of unit-test-scale workloads where overhead doesn’t matter, or when you need to compare two .prof files programmatically in CI. The Claude Skills 360 bundle includes pstats skill sets covering profile() context manager, profile_function() single-call profiler, load_stats()/merge_stats() data loaders, report() text report generator, FunctionProfile dataclass with top_functions() structured hotspot extractor, and ProfileDiff with compare_profiles() regression detector. Start with the free tier to try profiling analysis patterns and pstats pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free