{"id":13468797,"url":"https://github.com/rkern/line_profiler","last_synced_at":"2025-09-28T23:32:16.425Z","repository":{"id":20240267,"uuid":"23512354","full_name":"rkern/line_profiler","owner":"rkern","description":"(OLD REPO) Line-by-line profiling for Python - Current repo -\u003e","archived":true,"fork":false,"pushed_at":"2021-10-26T14:48:47.000Z","size":162,"stargazers_count":3608,"open_issues_count":70,"forks_count":256,"subscribers_count":86,"default_branch":"master","last_synced_at":"2024-12-30T05:54:18.521Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://github.com/pyutils/line_profiler","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rkern.png","metadata":{"files":{"readme":"README.rst","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-08-31T11:45:05.000Z","updated_at":"2024-12-27T12:39:27.000Z","dependencies_parsed_at":"2022-08-08T22:45:11.661Z","dependency_job_id":null,"html_url":"https://github.com/rkern/line_profiler","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkern%2Fline_profiler","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkern%2Fline_profiler/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkern%2Fline_profiler/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkern%2Fline_profiler/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rkern","download_url":"https://codeload.github.com/rkern/line_profiler/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234575214,"owners_count":18854924,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T15:01:19.261Z","updated_at":"2025-09-28T23:32:11.126Z","avatar_url":"https://github.com/rkern.png","language":"Python","readme":"line_profiler and kernprof\n--------------------------\n\n`line_profiler` is a module for doing line-by-line profiling of functions.\nkernprof is a convenient script for running either `line_profiler` or the Python\nstandard library's cProfile or profile modules, depending on what is available.\n\nThey are available under a `BSD license`_.\n\n.. _BSD license: https://raw.githubusercontent.com/rkern/line_profiler/master/LICENSE.txt\n\n.. contents::\n\n\nInstallation\n============\n\n**Note:** As of version 2.1.2, `pip install line_profiler` does not work.\nPlease install as follows until it is fixed in the next release::\n    \n    git clone https://github.com/rkern/line_profiler.git\n    find line_profiler -name '*.pyx' -exec cython {} \\;\n    cd line_profiler\n    pip install . --user \n\nReleases of `line_profiler` can be installed using pip::\n\n    $ pip install line_profiler\n\nSource releases and any binaries can be downloaded from the PyPI link.\n\n    http://pypi.python.org/pypi/line_profiler\n\nTo check out the development sources, you can use Git_::\n\n    $ git clone https://github.com/rkern/line_profiler.git\n\nYou may also download source tarballs of any snapshot from that URL.\n\nSource releases will require a C compiler in order to build `line_profiler`.\nIn addition, git checkouts will also require Cython_ \u003e= 0.10. Source releases\non PyPI should contain the pregenerated C sources, so Cython should not be\nrequired in that case.\n\n`kernprof` is a single-file pure Python script and does not require\na compiler.  If you wish to use it to run cProfile and not line-by-line\nprofiling, you may copy it to a directory on your `PATH` manually and avoid\ntrying to build any C extensions.\n\n.. _git: http://git-scm.com/\n.. _Cython: http://www.cython.org\n.. _build and install: http://docs.python.org/install/index.html\n\n\nline_profiler\n=============\n\nThe current profiling tools supported in Python 2.7 and later only time\nfunction calls. This is a good first step for locating hotspots in one's program\nand is frequently all one needs to do to optimize the program. However,\nsometimes the cause of the hotspot is actually a single line in the function,\nand that line may not be obvious from just reading the source code. These cases\nare particularly frequent in scientific computing. Functions tend to be larger\n(sometimes because of legitimate algorithmic complexity, sometimes because the\nprogrammer is still trying to write FORTRAN code), and a single statement\nwithout function calls can trigger lots of computation when using libraries like\nnumpy. cProfile only times explicit function calls, not special methods called\nbecause of syntax. Consequently, a relatively slow numpy operation on large\narrays like this, ::\n\n    a[large_index_array] = some_other_large_array\n\nis a hotspot that never gets broken out by cProfile because there is no explicit\nfunction call in that statement.\n\nLineProfiler can be given functions to profile, and it will time the execution\nof each individual line inside those functions. In a typical workflow, one only\ncares about line timings of a few functions because wading through the results\nof timing every single line of code would be overwhelming. However, LineProfiler\ndoes need to be explicitly told what functions to profile. The easiest way to\nget started is to use the `kernprof` script. ::\n\n    $ kernprof -l script_to_profile.py\n\n`kernprof` will create an instance of LineProfiler and insert it into the\n`__builtins__` namespace with the name `profile`. It has been written to be\nused as a decorator, so in your script, you decorate the functions you want\nto profile with @profile. ::\n\n    @profile\n    def slow_function(a, b, c):\n        ...\n\nThe default behavior of `kernprof` is to put the results into a binary file\nscript_to_profile.py.lprof . You can tell `kernprof` to immediately view the\nformatted results at the terminal with the [-v/--view] option. Otherwise, you\ncan view the results later like so::\n\n    $ python -m line_profiler script_to_profile.py.lprof\n\nFor example, here are the results of profiling a single function from\na decorated version of the pystone.py benchmark (the first two lines are output\nfrom `pystone.py`, not `kernprof`)::\n\n    Pystone(1.1) time for 50000 passes = 2.48\n    This machine benchmarks at 20161.3 pystones/second\n    Wrote profile results to pystone.py.lprof\n    Timer unit: 1e-06 s\n\n    File: pystone.py\n    Function: Proc2 at line 149\n    Total time: 0.606656 s\n\n    Line #      Hits         Time  Per Hit   % Time  Line Contents\n    ==============================================================\n       149                                           @profile\n       150                                           def Proc2(IntParIO):\n       151     50000        82003      1.6     13.5      IntLoc = IntParIO + 10\n       152     50000        63162      1.3     10.4      while 1:\n       153     50000        69065      1.4     11.4          if Char1Glob == 'A':\n       154     50000        66354      1.3     10.9              IntLoc = IntLoc - 1\n       155     50000        67263      1.3     11.1              IntParIO = IntLoc - IntGlob\n       156     50000        65494      1.3     10.8              EnumLoc = Ident1\n       157     50000        68001      1.4     11.2          if EnumLoc == Ident1:\n       158     50000        63739      1.3     10.5              break\n       159     50000        61575      1.2     10.1      return IntParIO\n\n\nThe source code of the function is printed with the timing information for each\nline. There are six columns of information.\n\n    * Line #: The line number in the file.\n\n    * Hits: The number of times that line was executed.\n\n    * Time: The total amount of time spent executing the line in the timer's\n      units. In the header information before the tables, you will see a line\n      \"Timer unit:\" giving the conversion factor to seconds. It may be different\n      on different systems.\n\n    * Per Hit: The average amount of time spent executing the line once in the\n      timer's units.\n\n    * % Time: The percentage of time spent on that line relative to the total\n      amount of recorded time spent in the function.\n\n    * Line Contents: The actual source code. Note that this is always read from\n      disk when the formatted results are viewed, *not* when the code was\n      executed. If you have edited the file in the meantime, the lines will not\n      match up, and the formatter may not even be able to locate the function\n      for display.\n\nIf you are using IPython, there is an implementation of an %lprun magic command\nwhich will let you specify functions to profile and a statement to execute. It\nwill also add its LineProfiler instance into the __builtins__, but typically,\nyou would not use it like that.\n\nFor IPython 0.11+, you can install it by editing the IPython configuration file\n`~/.ipython/profile_default/ipython_config.py` to add the `'line_profiler'`\nitem to the extensions list::\n\n    c.TerminalIPythonApp.extensions = [\n        'line_profiler',\n    ]\n\n\nTo get usage help for %lprun, use the standard IPython help mechanism::\n\n    In [1]: %lprun?\n\nThese two methods are expected to be the most frequent user-level ways of using\nLineProfiler and will usually be the easiest. However, if you are building other\ntools with LineProfiler, you will need to use the API. There are two ways to\ninform LineProfiler of functions to profile: you can pass them as arguments to\nthe constructor or use the `add_function(f)` method after instantiation. ::\n\n    profile = LineProfiler(f, g)\n    profile.add_function(h)\n\nLineProfiler has the same `run()`, `runctx()`, and `runcall()` methods as\ncProfile.Profile as well as `enable()` and `disable()`. It should be noted,\nthough, that `enable()` and `disable()` are not entirely safe when nested.\nNesting is common when using LineProfiler as a decorator. In order to support\nnesting, use `enable_by_count()` and `disable_by_count()`. These functions will\nincrement and decrement a counter and only actually enable or disable the\nprofiler when the count transitions from or to 0.\n\nAfter profiling, the `dump_stats(filename)` method will pickle the results out\nto the given file. `print_stats([stream])` will print the formatted results to\nsys.stdout or whatever stream you specify. `get_stats()` will return LineStats\nobject, which just holds two attributes: a dictionary containing the results and\nthe timer unit.\n\n\nkernprof\n========\n\n`kernprof` also works with cProfile, its third-party incarnation lsprof, or the\npure-Python profile module depending on what is available. It has a few main\nfeatures:\n\n    * Encapsulation of profiling concerns. You do not have to modify your script\n      in order to initiate profiling and save the results. Unless if you want to\n      use the advanced __builtins__ features, of course.\n\n    * Robust script execution. Many scripts require things like __name__,\n      __file__, and sys.path to be set relative to it. A naive approach at\n      encapsulation would just use execfile(), but many scripts which rely on\n      that information will fail. kernprof will set those variables correctly\n      before executing the script.\n\n    * Easy executable location. If you are profiling an application installed on\n      your PATH, you can just give the name of the executable. If kernprof does\n      not find the given script in the current directory, it will search your\n      PATH for it.\n\n    * Inserting the profiler into __builtins__. Sometimes, you just want to\n      profile a small part of your code. With the [-b/--builtin] argument, the\n      Profiler will be instantiated and inserted into your __builtins__ with the\n      name \"profile\". Like LineProfiler, it may be used as a decorator, or\n      enabled/disabled with `enable_by_count()` and `disable_by_count()`, or\n      even as a context manager with the \"with profile:\" statement.\n\n    * Pre-profiling setup. With the [-s/--setup] option, you can provide\n      a script which will be executed without profiling before executing the\n      main script. This is typically useful for cases where imports of large\n      libraries like wxPython or VTK are interfering with your results. If you\n      can modify your source code, the __builtins__ approach may be\n      easier.\n\nThe results of profile script_to_profile.py will be written to\nscript_to_profile.py.prof by default. It will be a typical marshalled file that\ncan be read with pstats.Stats(). They may be interactively viewed with the\ncommand::\n\n    $ python -m pstats script_to_profile.py.prof\n\nSuch files may also be viewed with graphical tools like kcachegrind_ through the\nconverter program pyprof2calltree_ or RunSnakeRun_.\n\n.. _kcachegrind: http://kcachegrind.sourceforge.net/html/Home.html\n.. _pyprof2calltree: http://pypi.python.org/pypi/pyprof2calltree/\n.. _RunSnakeRun: http://www.vrplumber.com/programming/runsnakerun/\n\n\nFrequently Asked Questions\n==========================\n\n* Why the name \"kernprof\"?\n\n    I didn't manage to come up with a meaningful name, so I named it after\n    myself.\n\n* Why not use hotshot instead of line_profile?\n\n    hotshot can do line-by-line timings, too. However, it is deprecated and may\n    disappear from the standard library. Also, it can take a long time to\n    process the results while I want quick turnaround in my workflows. hotshot\n    pays this processing time in order to make itself minimally intrusive to the\n    code it is profiling. Code that does network operations, for example, may\n    even go down different code paths if profiling slows down execution too\n    much. For my use cases, and I think those of many other people, their\n    line-by-line profiling is not affected much by this concern.\n\n* Why not allow using hotshot from kernprof.py?\n\n    I don't use hotshot, myself. I will accept contributions in this vein,\n    though.\n\n* The line-by-line timings don't add up when one profiled function calls\n  another. What's up with that?\n\n    Let's say you have function F() calling function G(), and you are using\n    LineProfiler on both. The total time reported for G() is less than the time\n    reported on the line in F() that calls G(). The reason is that I'm being\n    reasonably clever (and possibly too clever) in recording the times.\n    Basically, I try to prevent recording the time spent inside LineProfiler\n    doing all of the bookkeeping for each line. Each time Python's tracing\n    facility issues a line event (which happens just before a line actually gets\n    executed), LineProfiler will find two timestamps, one at the beginning\n    before it does anything (t_begin) and one as close to the end as possible\n    (t_end). Almost all of the overhead of LineProfiler's data structures\n    happens in between these two times.\n\n    When a line event comes in, LineProfiler finds the function it belongs to.\n    If it's the first line in the function, we record the line number and\n    *t_end* associated with the function. The next time we see a line event\n    belonging to that function, we take t_begin of the new event and subtract\n    the old t_end from it to find the amount of time spent in the old line. Then\n    we record the new t_end as the active line for this function. This way, we\n    are removing most of LineProfiler's overhead from the results. Well almost.\n    When one profiled function F calls another profiled function G, the line in\n    F that calls G basically records the total time spent executing the line,\n    which includes the time spent inside the profiler while inside G.\n\n    The first time this question was asked, the questioner had the G() function\n    call as part of a larger expression, and he wanted to try to estimate how\n    much time was being spent in the function as opposed to the rest of the\n    expression. My response was that, even if I could remove the effect, it\n    might still be misleading. G() might be called elsewhere, not just from the\n    relevant line in F(). The workaround would be to modify the code to split it\n    up into two lines, one which just assigns the result of G() to a temporary\n    variable and the other with the rest of the expression.\n\n    I am open to suggestions on how to make this more robust. Or simple\n    admonitions against trying to be clever.\n\n* Why do my list comprehensions have so many hits when I use the LineProfiler?\n\n    LineProfiler records the line with the list comprehension once for each\n    iteration of the list comprehension.\n\n* Why is kernprof distributed with line_profiler? It works with just cProfile,\n  right?\n\n    Partly because kernprof.py is essential to using line_profiler effectively,\n    but mostly because I'm lazy and don't want to maintain the overhead of two\n    projects for modules as small as these. However, kernprof.py is\n    a standalone, pure Python script that can be used to do function profiling\n    with just the Python standard library. You may grab it and install it by\n    itself without `line_profiler`.\n\n* Do I need a C compiler to build `line_profiler`? kernprof.py?\n\n    You do need a C compiler for line_profiler. kernprof.py is a pure Python\n    script and can be installed separately, though.\n\n* Do I need Cython to build `line_profiler`?\n\n    You should not have to if you are building from a released source tarball.\n    It should contain the generated C sources already. If you are running into\n    problems, that may be a bug; let me know. If you are building from\n    a git checkout or snapshot, you will need Cython to generate the\n    C sources. You will probably need version 0.10 or higher. There is a bug in\n    some earlier versions in how it handles NULL PyObject* pointers.\n\n* What version of Python do I need?\n\n    Both `line_profiler` and `kernprof` have been tested with Python 2.7, and\n    3.2-3.4.\n\n\nTo Do\n=====\n\ncProfile uses a neat \"rotating trees\" data structure to minimize the overhead of\nlooking up and recording entries. LineProfiler uses Python dictionaries and\nextension objects thanks to Cython. This mostly started out as a prototype that\nI wanted to play with as quickly as possible, so I passed on stealing the\nrotating trees for now. As usual, I got it working, and it seems to have\nacceptable performance, so I am much less motivated to use a different strategy\nnow. Maybe later. Contributions accepted!\n\n\nBugs and Such\n=============\n\nBugs and pull requested can be submitted on GitHub_.\n\n.. _GitHub: https://github.com/rkern/line_profiler\n\n\nChanges\n=======\n\n2.1\n~~~\n* ENH: Add support for Python 3.5 coroutines\n* ENH: Documentation updates\n* ENH: CI for most recent Python versions (3.5, 3.6, 3.6-dev, 3.7-dev, nightly)\n* ENH: Add timer unit argument for output time granularity spec\n\n2.0\n~~~\n* BUG: Added support for IPython 5.0+, removed support for IPython \u003c=0.12\n\n1.1\n~~~\n* BUG: Read source files as bytes.\n\n1.0\n~~~\n* ENH: `kernprof.py` is now installed as `kernprof`.\n* ENH: Python 3 support. Thanks to the long-suffering Mikhail Korobov for being\n  patient.\n* Dropped 2.6 as it was too annoying.\n* ENH: The `stripzeros` and `add_module` options. Thanks to Erik Tollerud for\n  contributing it.\n* ENH: Support for IPython cell blocks. Thanks to Michael Forbes for adding\n  this feature.\n* ENH: Better warnings when building without Cython. Thanks to David Cournapeau\n  for spotting this.\n\n1.0b3\n~~~~~\n\n* ENH: Profile generators.\n* BUG: Update for compatibility with newer versions of Cython. Thanks to Ondrej\n  Certik for spotting the bug.\n* BUG: Update IPython compatibility for 0.11+. Thanks to Yaroslav Halchenko and\n  others for providing the updated imports.\n\n1.0b2\n~~~~~\n\n* BUG: fixed line timing overflow on Windows.\n* DOC: improved the README.\n\n1.0b1\n~~~~~\n\n* Initial release.\n","funding_links":[],"categories":["Debugging Tools","Python","调试工具","Debugging Tools [🔝](#readme)","Awesome Python","Profiling"],"sub_categories":["Debugging Tools","Ranking/Recommender"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frkern%2Fline_profiler","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frkern%2Fline_profiler","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frkern%2Fline_profiler/lists"}