{"id":1652,"library":"pyinstrument","title":"Pyinstrument Profiler","description":"Pyinstrument is a powerful call stack profiler for Python that helps developers understand why their code is slow. It operates by sampling the call stack at regular intervals, providing a clear, interactive visualization of time spent in different functions. The current stable version is 5.1.2, and the library maintains an active release cadence with frequent updates addressing bugs and introducing new features, particularly around its HTML rendering capabilities.","status":"active","version":"5.1.2","language":"python","source_language":"en","source_url":"https://github.com/joerick/pyinstrument","tags":["profiler","performance","debugging","call stack","sampling","diagnostics"],"install":[{"cmd":"pip install pyinstrument","lang":"bash","label":"Install Pyinstrument"}],"dependencies":[],"imports":[{"symbol":"Profiler","correct":"from pyinstrument import Profiler"},{"symbol":"HTMLRenderer","correct":"from pyinstrument.renderers import HTMLRenderer"},{"symbol":"ConsoleRenderer","correct":"from pyinstrument.renderers import ConsoleRenderer"}],"quickstart":{"code":"from pyinstrument import Profiler\nimport time\nimport os\n\ndef my_slow_function():\n    time.sleep(0.05)\n    another_slow_part()\n\ndef another_slow_part():\n    time.sleep(0.02)\n\n# Using the context manager (recommended for specific code blocks)\nprofiler = Profiler()\nprofiler.start()\n\nfor _ in range(5):\n    my_slow_function()\n\nprofiler.stop()\n\n# Output to console\nprint(\"\\n--- Console Output ---\")\nprint(profiler.output_text(unicode=True, color=True))\n\n# Generate HTML report\n# For simplicity, we'll write to a file directly. In a real app,\n# you might return this HTML via a web framework.\nhtml_output = profiler.output_html()\noutput_filename = os.path.join(os.getcwd(), \"pyinstrument_profile.html\")\nwith open(output_filename, \"w\") as f:\n    f.write(html_output)\nprint(f\"\\nHTML report saved to: {output_filename}\")\nprint(\"Open the HTML file in your browser to view the interactive profile.\")","lang":"python","description":"This quickstart demonstrates how to profile a section of code using Pyinstrument's `Profiler` class and its `start()`/`stop()` methods, followed by generating both console text output and an interactive HTML report. For profiling an entire script from the command line, you can use `pyinstrument your_script.py`."},"warnings":[{"fix":"Review your profiling reports after upgrading to v5.0.0+ to ensure the 'library' code classification still aligns with your expectations. Adjust custom renderers or filtering if necessary.","message":"In Pyinstrument v5.0.0, the mechanism for detecting 'library' code (code not directly part of your application) was changed. This might alter how the profiler categorizes and displays frames, potentially affecting filtering or interpretation of results for users who relied on the previous classification.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"For critical performance measurements, compare results with and without the profiler. Use the `--interval` option (e.g., `pyinstrument --interval 0.0001`) to balance overhead and precision. Consider using the `with Profiler():` context manager for profiling only specific, critical sections of code to minimize overall impact.","message":"Pyinstrument, like most profilers, introduces some overhead. While it's designed to be low-overhead, profiling very short-lived functions or extremely high-frequency code paths can still show distorted results. The sampling interval (`--interval` CLI option or `Profiler(interval=...)` parameter) can affect both overhead and precision.","severity":"gotcha","affected_versions":"<5.1.0 (improved in 5.1.0)"},{"fix":"Always ensure `start()` and `stop()` calls are properly balanced. The `with Profiler() as profiler:` context manager (introduced in v4.7.0) is highly recommended as it automatically handles starting and stopping, even with exceptions, greatly reducing the chance of such errors.","message":"Mismatched calls to `profiler.start()` and `profiler.stop()` can lead to 'call stack without an active session' errors or incomplete profiles. This often happens in complex control flows or when exceptions interrupt profiling.","severity":"gotcha","affected_versions":"<5.1.2 (bug fixed in 5.1.2, but good practice remains)"},{"fix":"Upgrade to Pyinstrument v4.7.3 or newer to resolve compatibility issues with Python 3.12+ and libraries that modify `locals()` during execution.","message":"Pyinstrument versions prior to 4.7.3 could crash on Python 3.12 and later when profiling code that mutates the `locals()` dictionary, affecting compatibility with certain libraries (e.g., `glom`).","severity":"breaking","affected_versions":"<4.7.3 on Python 3.12+"}],"env_vars":null,"search_vec":"'5.1.2':47 'activ':53 'address':59 'around':66 'bug':60 'cadenc':55 'call':7,26,74 'capabl':70 'clear':33 'code':18 'current':43 'debug':73 'develop':14 'diagnost':77 'differ':40 'featur':64 'frequent':57 'function':41 'help':13 'html':68 'interact':34 'interv':30 'introduc':62 'librari':50 'maintain':51 'new':63 'oper':22 'particular':65 'perform':72 'power':6 'profil':2,9,71 'provid':31 'pyinstrument':1,3 'python':11 'regular':29 'releas':54 'render':69 'sampl':24,76 'slow':20 'spent':38 'stabl':44 'stack':8,27,75 'time':37 'understand':15 'updat':58 'version':45 'visual':35","created_at":"2026-04-09T03:57:19.078578+00:00","updated_at":"2026-04-16T18:30:07.420259+00:00","problems":[{"fix":"Ensure Pyinstrument is installed in the correct virtual environment using `pip install pyinstrument`. If issues persist, verify that the build process for your deployment environment allows C extensions to compile correctly, or consider using a Python version for which pre-built wheels for `pyinstrument_cext` are readily available.","cause":"This error occurs when the `pyinstrument_cext` C extension, a critical component of Pyinstrument, fails to compile or is not properly installed or located within the Python environment, particularly in restricted or containerized deployment settings like Docker or AWS Lambda.","error":"ModuleNotFoundError: No module named 'pyinstrument_cext'"},{"fix":"To resolve this, reduce the complexity of the profile by using command-line options like `--hide '*/lib/*'` or `--hide-regex '.*vendor.*'` to exclude irrelevant library code. Alternatively, in the Python API, adjust the `filter_threshold` when rendering the report or consider using alternative renderers such as `speedscope` for better visualization of large profiles.","cause":"The generated HTML profile report can become excessively large and complex, especially when profiling extensive codebases or using the `--show-all` option, which can cause web browsers to struggle with parsing and rendering the file efficiently due to resource limitations.","error":"Larger HTML files not loading in any browser"},{"fix":"Decrease the profiling interval to a smaller value to capture samples from very fast code. In the Python API, initialize the profiler with `profiler = Profiler(interval=0.0001)`. When using the command line, use the `--interval 0.0001` option.","cause":"This message indicates that the code being profiled executed too quickly for Pyinstrument's default sampling interval (which is 0.001 seconds or 1 millisecond) to capture any call stack samples during its execution.","error":"No samples were recorded."},{"fix":"Refactor your code to define any classes intended for pickling in a separate Python module and import them into your main script. If possible, ensure that the pickling operation occurs outside the section of code being profiled by Pyinstrument.","cause":"This occurs when Pyinstrument profiles a script that attempts to `pickle` (serialize) objects, particularly classes defined directly within the `__main__` scope of the script. The `pickle` module struggles to correctly resolve the `__main__` module's context when the script is executed by Pyinstrument.","error":"pyinstrument script.py where script.py contains a class serialized with pickle, you might encounter errors because the serialisation machinery doesn't know where __main__ is."}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"5.1.3","cli_name":"pyinstrument","cli_version":"pyinstrument 5.1.2, on Python 3.11.15","type":"library","homepage":"https://pyinstrument.readthedocs.io","github":"https://github.com/joerick/pyinstrument","docs":null,"changelog":null,"pypi":"https://pypi.org/project/pyinstrument/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["observability","devops"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-27","next_check":"2026-07-28","install_tag":null}}