---
name: codeflash-profile
user-invocable: false
disable-model-invocation: true
description: >-
  Profile a single Python function or module. Returns hotspot analysis with CPU time,
  memory allocation, and call counts. Activated when the user mentions "profile this function",
  "find the bottleneck", "what's slow in this code", "cProfile", "where is time spent",
  "tracemalloc", or "profile memory".
allowed-tools: "Bash, Read, Grep, Glob, Write"
---

# Profile a Python function or module

Profile the target the user described. Determine the profiling type from context.

## CPU profiling (default)

1. Identify the entry point: a test function, a script, or a module import
2. Run cProfile:
```bash
python -m cProfile -s cumulative -m pytest <test_file>::<test_func> 2>&1 | head -50
```
Or for a script:
```bash
python -m cProfile -s cumulative <script.py> 2>&1 | head -50
```

3. Parse the output and present a ranked table:
   - Function name
   - Total time (cumulative)
   - Own time (tottime)
   - Call count
   - File location

4. Highlight the top 5 hotspots with actionable analysis:
   - What the function does
   - Why it's slow (algorithm, I/O, allocation pattern)
   - Potential optimization direction

## Memory profiling

When the user's request is about memory, allocations, or RSS:

1. Run tracemalloc-based profiling:
```bash
python -c "
import tracemalloc
tracemalloc.start()
# Import or run the target
<user_target>
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics('lineno')[:20]:
    print(stat)
"
```

2. Present top allocators by size with file:line locations

## Import time profiling

When the user's request is about slow imports or startup time:

1. Run:
```bash
python -X importtime -c "import <module>" 2>&1 | sort -t'|' -k2 -rn | head -20
```

2. Present the import tree sorted by cumulative time
3. Identify candidates for lazy loading (imports > 10ms that aren't used at module level)

## Output format

Present results as a clean markdown table. End with a "Recommended next steps" section — if deeper optimization is warranted, suggest launching a full optimization session.
