line_profiler is a module for doing line-by-line profiling of functions, providing detailed timing statistics for each line within selected functions. kernprof is a companion script that conveniently runs line_profiler or Python's standard library profilers. It is currently at version 5.0.2 and actively maintained, with a release cadence that includes regular bug fixes and feature enhancements.
pip install line-profilerVerified import paths — ran on the pinned version, not inferred.
Create a file named `my_script.py` with the code above. To profile, you can either set the `LINE_PROFILE=1` environment variable and run `python my_script.py`, or use the `kernprof` command-line tool. The `kernprof -lvr my_script.py` command is recommended to enable line-by-line profiling, view results directly in the console (verbose), and utilize rich formatting if available.
Upgrade Python to 3.8 or newer, or pin `line-profiler<4.2.0`.
Upgrade to `line-profiler>=5.0.1` to mitigate performance issues and ensure correct multiprocessing output on Python 3.14+.
Interpret profiling results as relative performance indicators rather than absolute benchmarks. Run multiple times to average out variations.
For concurrent code, consider using profilers designed for such environments (e.g., `yappi` for multi-threading) or carefully isolate parts to profile one at a time.
Replace `enable()/disable()` with `enable_by_count()/disable_by_count()` for robust nested profiling.
Ensure Cython extensions are built with absolute paths for profiling builds, or investigate specific Cython build configurations that resolve this.
Install the package using pip: `pip install line_profiler`
Ensure `line_profiler` is installed (`pip install line_profiler`). If the issue persists, locate the `kernprof` executable (often in `~/.local/bin/` or a virtual environment's `bin` directory) and add its directory to your system's PATH, or run it directly using `python -m kernprof -l your_script.py`.
To fix this, either run your script with `kernprof -l your_script.py` (which injects `profile` globally), or for modern `line-profiler` versions (4.1.0+), import the decorator: `from line_profiler import profile` and ensure the `LINE_PROFILE=1` environment variable is set when running your script, or pass `--line-profile` to `python`.
Try reinstalling `line-profiler` after cleaning up previous installations: `pip uninstall line_profiler` then `pip install --no-cache-dir --force-reinstall line_profiler`. Ensure you have a C compiler installed if installing from source on platforms where wheels are not available.
Ensure you are running your script via `kernprof -l your_script.py`, which globally injects the `@profile` decorator. If you are trying to use it programmatically, import it specifically as `from line_profiler import LineProfiler, profile` (with `profile` being the decorator) or avoid `import profile` if using `kernprof`.