Skip to main content

Tracing & Workflows

Trace Python script execution and optimize functions based on real-world usage patterns.

codeflash optimize

Trace a Python script’s execution and optimize functions based on real-world usage.
codeflash optimize <script.py> [script_args]
# Basic trace and optimize
codeflash optimize app.py

# With script arguments
codeflash optimize process.py --input data.csv --output results.json

# Custom trace output file
codeflash optimize app.py --output custom_trace.trace

# With timeout (30 seconds)
codeflash optimize long_running_script.py --timeout 30

# Limit function trace count
codeflash optimize app.py --max-function-count 50

# Specify config file
codeflash optimize app.py --config-file-path pyproject.toml

# Local only (no PR)
codeflash optimize app.py --no-pr
How it works:
  1. Runs your script with the provided arguments
  2. Traces all function calls during execution
  3. Identifies which functions are called and how often
  4. Generates replay tests based on actual usage
  5. Optimizes the traced functions

Trace with pytest

Optimize functions called during pytest test execution.
# Trace pytest tests
codeflash optimize -m pytest tests/

# Trace specific test file
codeflash optimize -m pytest tests/test_core.py

# With pytest arguments
codeflash optimize -m pytest tests/ -v --tb=short
Tracing pytest tests is great for optimizing functions that are heavily used in your test suite, ensuring optimizations work correctly with your existing tests.

Trace Only (Generate Replay Tests)

Create trace files and replay tests without running optimization.
# Trace only - generates replay test
codeflash optimize app.py --output trace_file.trace --trace-only

# Then optimize using the replay test
codeflash --replay-test tests/test_app_py__replay_test_0.py --no-pr
Replay test naming: Files are named based on the traced script path. For src/app.py, the replay test will be named like test_srcapp_py__replay_test_0.py.
Use cases for trace-only:
  • Generate replay tests for later optimization
  • Debug tracing issues without running full optimization
  • Create reusable test cases from script execution

Replay Test Optimization

Optimize functions using previously generated replay tests.
codeflash --replay-test <path/to/replay_test.py>
# Optimize using replay test
codeflash --replay-test tests/test_app_py__replay_test_0.py --no-pr

# Multiple replay tests
codeflash --replay-test tests/test_*.py --no-pr

Next Steps