Performance Profiling
Goal
Provide tools to analyze simulation performance, identify bottlenecks, and recommend optimization strategies for computational materials science simulations.
Requirements
- Python 3.8+
- No external dependencies (uses Python standard library only)
- Works on Linux, macOS, and Windows
Inputs to Gather
Before running profiling scripts, collect from the user:
| Input |
Description |
Example |
| Simulation log |
Log file with timing information |
simulation.log |
| Scaling data |
JSON with multi-run performance data |
scaling_data.json |
| Simulation parameters |
JSON with mesh, fields, solver config |
params.json |
| Available memory |
System memory in GB (optional) |
16.0 |
Decision Guidance
When to Use Each Script
Need to identify slow phases?
├── YES → Use timing_analyzer.py
│ └── Parse simulation logs for timing data
│
Need to understand parallel performance?
├── YES → Use scaling_analyzer.py
│ └── Analyze strong or weak scaling efficiency
│
Need to estimate memory requirements?
├── YES → Use memory_profiler.py
│ └── Estimate memory from problem parameters
│
Need optimization recommendations?
└── YES → Use bottleneck_detector.py
└── Combine analyses and get actionable advice
Choosing Analysis Thresholds
| Metric |
Good |
Acceptable |
Poor |
| Phase dominance |
<30% |
30-50% |
>50% |
| Parallel efficiency |
>0.80 |
0.70-0.80 |
<0.70 |
| Memory usage |
<60% |
60-80% |
>80% |
Script Outputs (JSON Fields)
| Script |
Key Outputs |
timing_analyzer.py |
timing_data.phases, timing_data.slowest_phase, timing_data.total_time |
scaling_analyzer.py |
scaling_analysis.results, scaling_analysis.efficiency_threshold_processors |
memory_profiler.py |
memory_profile.total_memory_gb, memory_profile.per_process_gb, memory_profile.warnings |
bottleneck_detector.py |
bottlenecks, recommendations |
Workflow
Complete Profiling Workflow
- Analyze timing from simulation logs
- Analyze scaling from multi-run data (if available)
- Profile memory from simulation parameters
- Detect bottlenecks and get recommendations
- Implement optimizations based on recommendations
- Re-profile to verify improvements
Quick Profiling (Timing Only)
- Run timing analyzer on simulation log
- Identify dominant phases (>50% of runtime)
- Apply targeted optimizations to dominant phases
CLI Examples
Timing Analysis
# Basic timing analysis
python3 scripts/timing_analyzer.py \
--log simulation.log \
--json
# Custom timing pattern
python3 scripts/timing_analyzer.py \
--log simulation.log \
--pattern 'Step\s+(\w+)\s+took\s+([\d.]+)s' \
--json
Scaling Analysis
# Strong scaling (fixed problem size)
python3 scripts/scaling_analyzer.py \
--data scaling_data.json \
--type strong \
--json
# Weak scaling (constant work per processor)
python3 scripts/scaling_analyzer.py \
--data scaling_data.json \
--type weak \
--json
Memory Profiling
# Estimate memory requirements
python3 scripts/memory_profiler.py \
--params simulation_params.json \
--available-gb 16.0 \
--json
Bottleneck Detection
# Detect bottlenecks from timing only
python3 scripts/bottleneck_detector.py \
--timing timing_results.json \
--json
# Comprehensive analysis with all inputs
python3 scripts/bottleneck_detector.py \
--timing timing_results.json \
--scaling scaling_results.json \
--memory memory_results.json \
--json
Conversational Workflow Example
User: My simulation is taking too long. Can you help me identify what's slow?
Agent workflow:
- Ask for simulation log file
- Run timing analyzer:
python3 scripts/timing_analyzer.py --log simulation.log --json
- Interpret results:
- If solver dominates (>50%): Recommend preconditioner tuning
- If assembly dominates: Recommend caching or vectorization
- If I/O dominates: Recommend reducing output frequency
- If user has multi-run data, analyze scaling:
python3 scripts/scaling_analyzer.py --data scaling.json --type strong --json
- Generate comprehensive recommendations:
python3 scripts/bottleneck_detector.py --timing timing.json --scaling scaling.json --json
Interpretation Guidance
Timing Analysis
| Scenario |
Meaning |
Action |
| Solver >70% |
Solver-dominated |
Tune preconditioner, check tolerance |
| Assembly >50% |
Assembly-dominated |
Cache matrices, vectorize, parallelize |
| I/O >30% |
I/O-dominated |
Reduce frequency, use parallel I/O |
| Balanced (<30% each) |
Well-balanced |
Look for algorithmic improvements |
Scaling Analysis
| Efficiency |
Meaning |
Action |
| >0.80 |
Excellent scaling |
Continue scaling up |
| 0.70-0.80 |
Good scaling |
Monitor at larger scales |
| 0.50-0.70 |
Poor scaling |
Investigate communication/load balance |
| <0.50 |
Very poor scaling |
Reduce processor count or redesign |
Memory Profile
| Usage |
Meaning |
Action |
| <60% available |
Safe |
No action needed |
| 60-80% available |
Moderate |
Monitor, consider optimization |
| >80% available |
High |
Reduce resolution or increase processors |
| >100% available |
Exceeds capacity |
Must reduce problem size |
Error Handling
| Error |
Cause |
Resolution |
Log file not found |
Invalid path |
Verify log file path |
No timing data found |
Pattern mismatch |
Provide custom pattern with --pattern |
At least 2 runs required |
Insufficient data |
Provide more scaling runs |
Missing required parameters |
Incomplete params |
Add mesh and fields to params file |
Optimization Strategies by Bottleneck Type
Solver Bottlenecks
- Use algebraic multigrid (AMG) preconditioner
- Tighten solver tolerance if over-solving
- Consider direct solver for small problems
- Profile matrix assembly vs solve time
Assembly Bottlenecks
- Cache element matrices if geometry is static
- Use vectorized assembly routines
- Consider matrix-free methods
- Parallelize assembly with coloring
I/O Bottlenecks
- Reduce output frequency
- Use parallel I/O (HDF5, MPI-IO)
- Write to fast scratch storage
- Compress output data
Scaling Bottlenecks
- Investigate communication overhead
- Check for load imbalance
- Reduce synchronization points
- Use asynchronous communication
- Consider hybrid MPI+OpenMP
Memory Bottlenecks
- Reduce mesh resolution
- Use iterative solver (lower memory than direct)
- Enable out-of-core computation
- Increase number of processors
- Use single precision where appropriate
Security
The profiling scripts enforce the following safeguards when processing external data:
- File size limits: Log files capped at 500 MB, JSON files at 100 MB — rejected before parsing.
- JSON structure validation: All loaded JSON files must have an object (dict) as root element.
- Regex pattern validation: User-supplied
--pattern values are validated for length (500 chars max) and rejected if they contain constructs prone to catastrophic backtracking (ReDoS).
- Phase name sanitization: Phase names extracted from log files are truncated to 200 characters and stripped of control characters to prevent prompt-injection payloads from propagating into agent context.
- Scaling data validation: Run entries validated for finite time values, integer processor counts, and bounded run count (10,000 max).
- Memory parameter validation:
available_gb validated as positive finite number; mesh dimensions and field parameters validated as positive integers.
- Reduced tool surface: The skill's
allowed-tools excludes Bash to prevent the agent from executing arbitrary commands when processing untrusted simulation logs or result files.
Limitations
- Log parsing: Depends on pattern matching; may miss unusual formats
- Scaling analysis: Requires at least 2 runs for meaningful results
- Memory estimation: Approximate; actual usage may vary
- Recommendations: General guidance; may need domain-specific tuning
References
references/profiling_guide.md - Profiling concepts and interpretation
references/optimization_strategies.md - Detailed optimization approaches
Version History
- v1.0.0 (2025-01-22): Initial release with 4 profiling scripts
1---2name: performance-profiling-93description: Identify computational bottlenecks, analyze scaling behavior, estimate memory requirements, and receive optimization recommendations for any computational simulation. Use when simulations are slow, investigating parallel efficiency, planning resource allocation, or seeking performance improvements through timing analysis, scaling studies, memory profiling, or bottleneck detection.4---5
6# Performance Profiling
7
8## Goal
9
10Provide tools to analyze simulation performance, identify bottlenecks, and recommend optimization strategies for computational materials science simulations.
11
12## Requirements
13
14- Python 3.8+
15- No external dependencies (uses Python standard library only)
16- Works on Linux, macOS, and Windows
17
18## Inputs to Gather
19
20Before running profiling scripts, collect from the user:
21
22| Input | Description | Example |
23|-------|-------------|---------|
24| Simulation log | Log file with timing information | `simulation.log` |
25| Scaling data | JSON with multi-run performance data | `scaling_data.json` |
26| Simulation parameters | JSON with mesh, fields, solver config | `params.json` |
27| Available memory | System memory in GB (optional) | `16.0` |
28
29## Decision Guidance
30
31### When to Use Each Script
32
33```
34Need to identify slow phases?
35├── YES → Use timing_analyzer.py
36│ └── Parse simulation logs for timing data
37│
38Need to understand parallel performance?
39├── YES → Use scaling_analyzer.py
40│ └── Analyze strong or weak scaling efficiency
41│
42Need to estimate memory requirements?
43├── YES → Use memory_profiler.py
44│ └── Estimate memory from problem parameters
45│
46Need optimization recommendations?
47└── YES → Use bottleneck_detector.py
48 └── Combine analyses and get actionable advice
49```
50
51### Choosing Analysis Thresholds
52
53| Metric | Good | Acceptable | Poor |
54|--------|------|------------|------|
55| Phase dominance | <30% | 30-50% | >50% |
56| Parallel efficiency | >0.80 | 0.70-0.80 | <0.70 |
57| Memory usage | <60% | 60-80% | >80% |
58
59## Script Outputs (JSON Fields)
60
61| Script | Key Outputs |
62|--------|-------------|
63| `timing_analyzer.py` | `timing_data.phases`, `timing_data.slowest_phase`, `timing_data.total_time` |
64| `scaling_analyzer.py` | `scaling_analysis.results`, `scaling_analysis.efficiency_threshold_processors` |
65| `memory_profiler.py` | `memory_profile.total_memory_gb`, `memory_profile.per_process_gb`, `memory_profile.warnings` |
66| `bottleneck_detector.py` | `bottlenecks`, `recommendations` |
67
68## Workflow
69
70### Complete Profiling Workflow
71
721. **Analyze timing** from simulation logs
732. **Analyze scaling** from multi-run data (if available)
743. **Profile memory** from simulation parameters
754. **Detect bottlenecks** and get recommendations
765. **Implement optimizations** based on recommendations
776. **Re-profile** to verify improvements
78
79### Quick Profiling (Timing Only)
80
811. **Run timing analyzer** on simulation log
822. **Identify dominant phases** (>50% of runtime)
833. **Apply targeted optimizations** to dominant phases
84
85## CLI Examples
86
87### Timing Analysis
88
89```bash
90# Basic timing analysis
91python3 scripts/timing_analyzer.py \
92 --log simulation.log \
93 --json
94
95# Custom timing pattern
96python3 scripts/timing_analyzer.py \
97 --log simulation.log \
98 --pattern 'Step\s+(\w+)\s+took\s+([\d.]+)s' \
99 --json
100```
101
102### Scaling Analysis
103
104```bash
105# Strong scaling (fixed problem size)
106python3 scripts/scaling_analyzer.py \
107 --data scaling_data.json \
108 --type strong \
109 --json
110
111# Weak scaling (constant work per processor)
112python3 scripts/scaling_analyzer.py \
113 --data scaling_data.json \
114 --type weak \
115 --json
116```
117
118### Memory Profiling
119
120```bash
121# Estimate memory requirements
122python3 scripts/memory_profiler.py \
123 --params simulation_params.json \
124 --available-gb 16.0 \
125 --json
126```
127
128### Bottleneck Detection
129
130```bash
131# Detect bottlenecks from timing only
132python3 scripts/bottleneck_detector.py \
133 --timing timing_results.json \
134 --json
135
136# Comprehensive analysis with all inputs
137python3 scripts/bottleneck_detector.py \
138 --timing timing_results.json \
139 --scaling scaling_results.json \
140 --memory memory_results.json \
141 --json
142```
143
144## Conversational Workflow Example
145
146**User**: My simulation is taking too long. Can you help me identify what's slow?
147
148**Agent workflow**:
1491. Ask for simulation log file
1502. Run timing analyzer:
151 ```bash
152 python3 scripts/timing_analyzer.py --log simulation.log --json
153 ```
1543. Interpret results:
155 - If solver dominates (>50%): Recommend preconditioner tuning
156 - If assembly dominates: Recommend caching or vectorization
157 - If I/O dominates: Recommend reducing output frequency
1584. If user has multi-run data, analyze scaling:
159 ```bash
160 python3 scripts/scaling_analyzer.py --data scaling.json --type strong --json
161 ```
1625. Generate comprehensive recommendations:
163 ```bash
164 python3 scripts/bottleneck_detector.py --timing timing.json --scaling scaling.json --json
165 ```
166
167## Interpretation Guidance
168
169### Timing Analysis
170
171| Scenario | Meaning | Action |
172|----------|---------|--------|
173| Solver >70% | Solver-dominated | Tune preconditioner, check tolerance |
174| Assembly >50% | Assembly-dominated | Cache matrices, vectorize, parallelize |
175| I/O >30% | I/O-dominated | Reduce frequency, use parallel I/O |
176| Balanced (<30% each) | Well-balanced | Look for algorithmic improvements |
177
178### Scaling Analysis
179
180| Efficiency | Meaning | Action |
181|------------|---------|--------|
182| >0.80 | Excellent scaling | Continue scaling up |
183| 0.70-0.80 | Good scaling | Monitor at larger scales |
184| 0.50-0.70 | Poor scaling | Investigate communication/load balance |
185| <0.50 | Very poor scaling | Reduce processor count or redesign |
186
187### Memory Profile
188
189| Usage | Meaning | Action |
190|-------|---------|--------|
191| <60% available | Safe | No action needed |
192| 60-80% available | Moderate | Monitor, consider optimization |
193| >80% available | High | Reduce resolution or increase processors |
194| >100% available | Exceeds capacity | Must reduce problem size |
195
196## Error Handling
197
198| Error | Cause | Resolution |
199|-------|-------|------------|
200| `Log file not found` | Invalid path | Verify log file path |
201| `No timing data found` | Pattern mismatch | Provide custom pattern with --pattern |
202| `At least 2 runs required` | Insufficient data | Provide more scaling runs |
203| `Missing required parameters` | Incomplete params | Add mesh and fields to params file |
204
205## Optimization Strategies by Bottleneck Type
206
207### Solver Bottlenecks
208- Use algebraic multigrid (AMG) preconditioner
209- Tighten solver tolerance if over-solving
210- Consider direct solver for small problems
211- Profile matrix assembly vs solve time
212
213### Assembly Bottlenecks
214- Cache element matrices if geometry is static
215- Use vectorized assembly routines
216- Consider matrix-free methods
217- Parallelize assembly with coloring
218
219### I/O Bottlenecks
220- Reduce output frequency
221- Use parallel I/O (HDF5, MPI-IO)
222- Write to fast scratch storage
223- Compress output data
224
225### Scaling Bottlenecks
226- Investigate communication overhead
227- Check for load imbalance
228- Reduce synchronization points
229- Use asynchronous communication
230- Consider hybrid MPI+OpenMP
231
232### Memory Bottlenecks
233- Reduce mesh resolution
234- Use iterative solver (lower memory than direct)
235- Enable out-of-core computation
236- Increase number of processors
237- Use single precision where appropriate
238
239## Security
240
241The profiling scripts enforce the following safeguards when processing external data:
242
243- **File size limits**: Log files capped at 500 MB, JSON files at 100 MB — rejected before parsing.
244- **JSON structure validation**: All loaded JSON files must have an object (dict) as root element.
245- **Regex pattern validation**: User-supplied `--pattern` values are validated for length (500 chars max) and rejected if they contain constructs prone to catastrophic backtracking (ReDoS).
246- **Phase name sanitization**: Phase names extracted from log files are truncated to 200 characters and stripped of control characters to prevent prompt-injection payloads from propagating into agent context.
247- **Scaling data validation**: Run entries validated for finite time values, integer processor counts, and bounded run count (10,000 max).
248- **Memory parameter validation**: `available_gb` validated as positive finite number; mesh dimensions and field parameters validated as positive integers.
249- **Reduced tool surface**: The skill's `allowed-tools` excludes `Bash` to prevent the agent from executing arbitrary commands when processing untrusted simulation logs or result files.
250
251## Limitations
252
253- **Log parsing**: Depends on pattern matching; may miss unusual formats
254- **Scaling analysis**: Requires at least 2 runs for meaningful results
255- **Memory estimation**: Approximate; actual usage may vary
256- **Recommendations**: General guidance; may need domain-specific tuning
257
258## References
259
260- `references/profiling_guide.md` - Profiling concepts and interpretation
261- `references/optimization_strategies.md` - Detailed optimization approaches
262
263## Version History
264
265- **v1.0.0** (2025-01-22): Initial release with 4 profiling scripts
266