Line-by-line profiler

5.0.2 · active · verified Fri Apr 10

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.

Warnings

Install

Imports

Quickstart

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.

import time
from line_profiler import profile
import os

@profile
def slow_function_one():
    time.sleep(0.01)
    [x * x for x in range(1000)] # This line will be profiled

@profile
def slow_function_two(iterations):
    data = []
    for _ in range(iterations):
        data.append(sum(range(100)))
    time.sleep(0.02)

def main():
    print('Starting profiling demo...')
    slow_function_one()
    slow_function_two(1000)
    print('Profiling demo finished.')

if __name__ == '__main__':
    # Method 1: Run with environment variable (requires line_profiler to be imported and decorated)
    #   To run: LINE_PROFILE=1 python my_script.py
    #   Output will be printed to console and .lprof file generated.

    # Method 2: Run directly via kernprof CLI (recommended for explicit control)
    #   To run: kernprof -lvr my_script.py
    #   -l enables line-by-line profiling
    #   -v prints results to stdout
    #   -r enables rich output (if 'rich' is installed)

    # This block ensures the script is runnable even without explicit kernprof or env var
    if os.environ.get('LINE_PROFILE') == '1':
        main()
    else:
        # For direct execution without profiling enabled, or if kernprof handles execution
        main()

view raw JSON →