Pyinstrument - a Python profiler. A profiler is a tool to help you optimize your code - make it faster.

Overview

pyinstrument

PyPI version .github/workflows/test.yml Build wheels

Documentation

Screenshot

Pyinstrument is a Python profiler. A profiler is a tool to help you optimize your code - make it faster. To get the biggest speed increase you should focus on the slowest part of your program. Pyinstrument helps you find it!

Installation

pip install pyinstrument

Pyinstrument supports Python 3.7+.

To run Pyinstrument from a git checkout, there's a build step. Take a look at Contributing for more info.

Documentation

To learn how to use pyinstrument, or to check the reference, head to the documentation.

Known issues

  • Profiling code inside a Docker container can cause some strange results, because the gettimeofday syscall that pyinstrument uses is slow in that environment. See #83
  • When using 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. See this issue for workarounds

Changelog

v4.1.1

  • Fixed an issue causing PYINSTRUMENT_PROFILE_DIR_RENDERER to output the wrong file extension when used with the speedscope renderer.

v4.1.0

  • You can now use pyinstrument natively in an IPython notebook! Just use %load_ext pyinstrument at the top of your notebook, and then %%pyinstrument in the cell you want to profile.
  • Added support for the speedscope format. This provides a way to view interactive flamecharts using pyinstrument. To use, profile with pyinstrument -r speedscope, and upload to the speedscope web app.
  • You can now configure renderers for the Django middleware file output, using the PYINSTRUMENT_PROFILE_DIR_RENDERER option.
  • Added wheels for Linux aarch64 (64-bit ARM).

v4.0.4

  • Fix a packaging issue where a package called 'test' was installed alongside pyinstrument
  • Use more modern C APIs to resolve deprecation warnings on Python 3.10.
  • Minor docs fixes

v4.0.3

  • CPython 3.10 support
  • Improve error messages when trying to use Profiler from multiple threads
  • Fix crash when rendering sessions that contain a module in a FrameGroup

v4.0.2

  • Fix some packaging issues

v4.0.0

  • Async support! Pyinstrument now detects when an async task hits an await, and tracks time spent outside of the async context under this await.

    So, for example, here's a simple script with an async task that does a sleep:

    import asyncio
    from pyinstrument import Profiler
    
    async def main():
        p = Profiler(async_mode='disabled')
    
        with p:
            print('Hello ...')
            await asyncio.sleep(1)
            print('... World!')
    
        p.print()
    
    asyncio.run(main())

    Before Pyinstrument 4.0.0, we'd see only time spent in the run loop, like this:

      _     ._   __/__   _ _  _  _ _/_   Recorded: 18:33:03  Samples:  2
     /_//_/// /_\ / //_// / //_'/ //     Duration: 1.006     CPU time: 0.001
    /   _/                      v3.4.2
    
    Program: examples/async_example_simple.py
    
    1.006 _run_once  asyncio/base_events.py:1784
    └─ 1.005 select  selectors.py:553
          [3 frames hidden]  selectors, 
         
          
             1.005 kqueue.control  
          
           :0
    
          
         

    Now, with pyinstrument 4.0.0, we get:

      _     ._   __/__   _ _  _  _ _/_   Recorded: 18:30:43  Samples:  2
     /_//_/// /_\ / //_// / //_'/ //     Duration: 1.007     CPU time: 0.001
    /   _/                      v4.0.0
    
    Program: examples/async_example_simple.py
    
    1.006 main  async_example_simple.py:4
    └─ 1.005 sleep  asyncio/tasks.py:641
          [2 frames hidden]  asyncio
             1.005 [await]
    

    For more information, check out the async profiling documentation and the Profiler.async_mode property.

  • Pyinstrument has a documentation site, including full Python API docs!

v3.4.2

  • Fix a bug that caused --show, --show-regex, --show-all to be ignored on the command line.

v3.4.1

  • Under-the-hood modernisation

v3.4.0

  • Added timeline option (boolean) to Profiler methods output_html() and open_in_browser().

v3.3.0

  • Fixed issue with pyinstrument -m module, where pyinstrument wouldn't find modules in the current directory.
  • Dropped support for Python 2.7 and 3.5. Old versions will remain available on PyPI, and pip should choose the correct one automatically.

v3.2.0

  • Added the ability to track time in C functions. Minor note - Pyinstrument will record time spent C functions as 'leaf' functions, due to a limitation in how Python records frames. Python -> C -> Python is recorded as Python -> Python, but Python -> Python -> C will be attributed correctly. (#103)

v3.1.2

  • Fix <__array_function__ internals> frames appearing as app code in reports

v3.1.1

  • Added support for timeline mode on HTML and JSON renderers
  • Released as a tarball as well as a universal wheel

v3.1.0

  • Added PYINSTRUMENT_SHOW_CALLBACK option on the Django middleware to add a condition to showing the profile (could be used to run pyinstrument on a live server!)
  • Fixed bug in the Django middleware where file would not be written because of a unicode error

v3.0.3

  • Fixed bug with the Django middleware on Windows where profiling would fail because we were trying to put an illegal character '?' in the profile path. (#66)

v3.0.2

  • Add --show and --show-regex options, to mark certain files to be displayed. This helps to profile inside specific modules, while hiding others. For example, pyinstrument --show '*/sympy/*' script.py.

v3.0.1

  • Fix #60: pass all arguments after -m module_name to the called module
  • Fix crash during HTML/JSON output when no frames were captured.

v3.0.0

  • Pyinstrument will now hide traces through libraries that you're using by default. So instead of showing you loads of frames going through the internals of something external e.g. urllib, it lets you focus on your code.

    Before After
    image image

    To go back to the old behaviour, use --show-all on the command line.

  • 'Entry' frames of hidden groups are shown, so you know which call is the problem

  • Really slow frames in the groups are shown too, e.g. the 'read' call on the socket

  • Application code is highlighted in the console

  • Additional metrics are shown at the top of the trace - timestamp, number of samples, duration, CPU time

  • Hidden code is controlled by the --hide or --hide-regex options - matching on the path of the code files.

      --hide=EXPR           glob-style pattern matching the file paths whose
                            frames to hide. Defaults to '*/lib/*'.
      --hide-regex=REGEX    regex matching the file paths whose frames to hide.
                            Useful if --hide doesn't give enough control.
    
  • Outputting a timeline is supported from the command line.

      -t, --timeline        render as a timeline - preserve ordering and don't
                            condense repeated calls
    
  • Because there are a few rendering options now, you can load a previous profiling session using --load-prev - pyinstrument keeps the last 10 sessions.

  • Hidden groups can also call back into application code, that looks like this:

    image

  • (internal) When recording timelines, frame trees are completely linear now, allowing for the creation of super-accurate frame charts.

  • (internal) The HTML renderer has been rewritten as a Vue.js app. All the console improvements apply to the HTML output too, plus it's interactive.

  • (internal) A lot of unit and integration tests added!

Yikes! See #49 for the gory details. I hope you like it.

v2.3.0

  • Big refactor!
    • Recorders have been removed. The frame recording is now internal to the Profiler object. This means the 'frame' objects are more general-purpose, which paves the way for...
    • Processors! These are functions that mutate the tree to sculpt the output. They are used by the renderers to filter the output to the correct form. Now, instead of a time-aggregating recorder, the profiler just uses timeline-style recording (this is lower-overhead anyway) and the aggregation is done as a processing step.
    • The upshot of this is that it's now way easier to alter the tree to filter stuff out, and do more advanced things like combining frames that we don't care about. More features to come that use this in v3.0!
  • Importlib frames are removed - you won't see them at all. Their children are retained, so imports are just transparent.
  • Django profile file name is now limited to a hundred of characters (#50)
  • Fix bug with --html option (#53)
  • Add --version command line option

v2.2.1

  • Fix crash when using on the command line.

v2.2.0

  • Added support for JSON output. Use pyinstrument --renderer=json scriptfile.py. PR

  • @iddan has put together an interactive viewer using the JSON output!

    image

  • When running pyinstrument --html and you don't pipe the output to a file, pyinstrument will write the console output to a temp file and open that in a browser.

v2.1.0

  • Added support for running modules with pyinstrument via the command line. The new syntax is the -m flag e.g. pyinstrument -m module_name! PR

v2.0.4

v2.0.3

  • Pyinstrument can now be used in a with block.

    For example:

    profiler = pyinstrument.Profiler()
    with profiler:
        # do some work here...
    print(profiler.output_text())
    
  • Middleware fix for older versions of Django

v2.0.2

  • Fix for max recursion error when used to profile programs with a lot of frames on the stack.

v2.0.1

  • Ensure license is included in the sdist.

v2.0.0

  • Pyinstrument uses a new profiling mode. Rather than using signals, pyintrument uses a new statistical profiler built on PyEval_SetProfile. This means no more main thread restriction, no more IO errors when using Pyinstrument, and no need for a separate more 'setprofile' mode!

  • Renderers. Users can customize Pyinstrument to use alternative renderers with the renderer argument on Profiler.output(), or using the --renderer argument on the command line.

  • Recorders. To support other use cases of Pyinstrument (e.g. flame charts), pyinstrument now has a 'timeline' recorder mode. This mode records captured frames in a linear way, so the program execution can be viewed on a timeline.

v0.13

  • pyinstrument command. You can now profile python scripts from the shell by running $ pyinstrument script.py. This is now equivalent to python -m pyinstrument. Thanks @asmeurer!

v0.12

  • Application code is highlighted in HTML traces to make it easier to spot

  • Added PYINSTRUMENT_PROFILE_DIR option to the Django interface, which will log profiles of all requests to a file the specified folder. Useful for profiling API calls.

  • Added PYINSTRUMENT_USE_SIGNAL option to the Django interface, for use when signal mode presents problems.

Contributing

To setup a dev environment:

virtualenv --python=python3 env
. env/bin/activate
pip install --upgrade pip
pip install -r requirements-dev.txt
pre-commit install --install-hooks

To get some sample output:

pyinstrument examples/wikipedia_article_word_count.py

To run the tests:

pytest

To run linting checks locally:

pre-commit run --all-files

Some of the pre-commit checks, like isort or black, will auto-fix the problems they find. So if the above command returns an error, try running it again, it might succeed the second time :)

Running all the checks can be slow, so you can also run checks individually, e.g., to format source code that fails isort or black checks:

pre-commit run --all-files isort
pre-commit run --all-files black

To diagnose why pyright checks are failing:

pre-commit run --all-files pyright

The HTML renderer Vue.js app

The HTML renderer works by embedding a JSON representation of the sample with a Javascript 'bundle' inside an HTML file that can be viewed in any web browser.

To edit the html renderer style, do:

cd html_renderer
npm ci
npm run serve

When launched without a top-level window.profileSession object, it will fetch a sample profile so you can work with it.

To compile the JS app and bundle it back into the pyinstrument python tool:

bin/build_js_bundle.py [--force]
Owner
Joe Rickerby
Technologist @nordprojects. @pypa maintainer.
Joe Rickerby
A package containing a lot of useful utilities for Python developing and debugging.

Vpack A package containing a lot of useful utilities for Python developing and debugging. Features Sigview: press Ctrl+C to print the current stack in

volltin 16 Aug 18, 2022
EDB 以太坊单合约交易调试工具

EDB 以太坊单合约交易调试工具 Idea 在刷题的时候遇到一类JOP(Jump-Oriented-Programming)的题目,fuzz或者调试这类题目缺少简单易用的工具,由此开发了一个简单的调试工具EDB(The Ethereum Debugger),利用debug_traceTransact

16 May 21, 2022
🔥 Pyflame: A Ptracing Profiler For Python. This project is deprecated and not maintained.

Pyflame: A Ptracing Profiler For Python (This project is deprecated and not maintained.) Pyflame is a high performance profiling tool that generates f

Uber Archive 3k Jan 07, 2023
Automated bug/error reporting for napari

napari-error-monitor Want to help out napari? Install this plugin! This plugin will automatically send error reports to napari (via sentry.io) wheneve

Talley Lambert 2 Sep 15, 2022
Arghonaut is an interactive interpreter, visualizer, and debugger for Argh! and Aargh!

Arghonaut Arghonaut is an interactive interpreter, visualizer, and debugger for Argh! and Aargh!, which are Befunge-like esoteric programming language

Aaron Friesen 2 Dec 10, 2021
Middleware that Prints the number of DB queries to the runserver console.

Django Querycount Inspired by this post by David Szotten, this project gives you a middleware that prints DB query counts in Django's runserver consol

Brad Montgomery 332 Dec 23, 2022
NoPdb: Non-interactive Python Debugger

NoPdb: Non-interactive Python Debugger Installation: pip install nopdb Docs: https://nopdb.readthedocs.io/ NoPdb is a programmatic (non-interactive) d

Ondřej Cífka 67 Oct 15, 2022
Little helper to run Steam apps under Proton with a GDB debugger

protongdb A small little helper for running games with Proton and debugging with GDB Requirements At least Python 3.5 protontricks pip package and its

Joshie 21 Nov 27, 2022
Full-screen console debugger for Python

PuDB: a console-based visual debugger for Python Its goal is to provide all the niceties of modern GUI-based debuggers in a more lightweight and keybo

Andreas Klöckner 2.6k Jan 01, 2023
PINCE is a front-end/reverse engineering tool for the GNU Project Debugger (GDB), focused on games.

PINCE is a front-end/reverse engineering tool for the GNU Project Debugger (GDB), focused on games. However, it can be used for any reverse-engi

Korcan Karaokçu 1.5k Jan 01, 2023
Cyberbrain: Python debugging, redefined.

Cyberbrain1(电子脑) aims to free programmers from debugging.

laike9m 2.3k Jan 07, 2023
A web-based visualization and debugging platform for NuPIC

Cerebro 2 A web-based visualization and debugging platform for NuPIC. Usage Set up cerebro2.server to export your model state. Then, run: cd static py

Numenta 24 Oct 13, 2021
A drop-in replacement for Django's runserver.

About A drop in replacement for Django's built-in runserver command. Features include: An extendable interface for handling things such as real-time l

David Cramer 1.3k Dec 15, 2022
🍦 Never use print() to debug again.

IceCream -- Never use print() to debug again Do you ever use print() or log() to debug your code? Of course you do. IceCream, or ic for short, makes p

Ansgar Grunseid 6.5k Jan 07, 2023
一个小脚本,用于trace so中native函数的调用。

trace_natives 一个IDA小脚本,获取SO代码段中所有函数的偏移地址,再使用frida-trace 批量trace so函数的调用。 使用方法 1.将traceNatives.py丢进IDA plugins目录中 2.IDA中,Edit-Plugins-traceNatives IDA输

296 Dec 28, 2022
Visual Interaction with Code - A portable visual debugger for python

VIC Visual Interaction with Code A simple tool for debugging and interacting with running python code. This tool is designed to make it easy to inspec

Nathan Blank 1 Nov 16, 2021
pdb++, a drop-in replacement for pdb (the Python debugger)

pdb++, a drop-in replacement for pdb What is it? This module is an extension of the pdb module of the standard library. It is meant to be fully compat

1k Jan 02, 2023
Voltron is an extensible debugger UI toolkit written in Python.

Voltron is an extensible debugger UI toolkit written in Python. It aims to improve the user experience of various debuggers (LLDB, GDB, VDB an

snare 5.9k Dec 30, 2022
Hunter is a flexible code tracing toolkit.

Overview docs tests package Hunter is a flexible code tracing toolkit, not for measuring coverage, but for debugging, logging, inspection and other ne

Ionel Cristian Mărieș 705 Dec 08, 2022
Never use print for debugging again

PySnooper - Never use print for debugging again PySnooper is a poor man's debugger. If you've used Bash, it's like set -x for Python, except it's fanc

Ram Rachum 15.5k Jan 01, 2023