{"id":17360801,"url":"https://github.com/certik/line_profiler","last_synced_at":"2025-04-15T00:31:35.527Z","repository":{"id":973981,"uuid":"772029","full_name":"certik/line_profiler","owner":"certik","description":null,"archived":false,"fork":false,"pushed_at":"2010-07-15T17:57:08.000Z","size":209,"stargazers_count":23,"open_issues_count":0,"forks_count":7,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-03-28T12:38:42.446Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","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/certik.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":"2010-07-13T07:52:14.000Z","updated_at":"2024-09-05T09:19:14.000Z","dependencies_parsed_at":"2022-08-16T11:40:30.374Z","dependency_job_id":null,"html_url":"https://github.com/certik/line_profiler","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/certik%2Fline_profiler","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/certik%2Fline_profiler/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/certik%2Fline_profiler/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/certik%2Fline_profiler/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/certik","download_url":"https://codeload.github.com/certik/line_profiler/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248984292,"owners_count":21193719,"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-10-15T19:28:19.011Z","updated_at":"2025-04-15T00:31:35.240Z","avatar_url":"https://github.com/certik.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"line_profiler and kernprof\n--------------------------\n\nline_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: http://github.com/certik/line_profiler/raw/master/LICENSE.txt\n\n.. contents::\n\n\nInstallation\n============\n\nSource releases and any binaries can be downloaded from the PyPI link.\n\n    http://pypi.python.org/pypi/line_profiler\n\nThe current release of the kernprof.py script may be downloaded separately here:\n\n    http://packages.python.org/line_profiler/kernprof.py\n\nTo check out the development sources, you can use Git_::\n\n    $ git clone git://github.com/certik/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. In\naddition, Mercurial 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\nkernprof.py is a single-file pure Python script and does not require a compiler.\nIf you wish to use it to run cProfile and not line-by-line profiling, you may\ncopy it to a directory on your PATH manually and avoid trying to build any\nC extensions.\n\nIn order to build and install line_profiler, you will simply use the standard\n`build and install`_ for most Python packages::\n\n    $ python setup.py install\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.5 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.py script.\n\nIf you use ``kernprof.py -l script_to_profile.py``, an instance\nof LineProfiler will be created and inserted into the __builtins__ namespace\nwith the name \"profile\". It has been written to be used as a decorator, so in\nyour script, you can decorate any function you want to 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. You can install it by editing the IPython\nconfiguration file ~/.ipython/ipy_user_conf.py to add the following lines::\n\n    # These two lines are standard and probably already there.\n    import IPython.ipapi\n    ip = IPython.ipapi.get()\n\n    # These two are the important ones.\n    import line_profiler\n    ip.expose_magic('lprun', line_profiler.magic_lprun)\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\nkernprof 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 in Python 2.5\n      and 2.6.\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 Mercurial 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.4 and Python\n    2.5. It might work with Python 2.3, and will probably work with Python 2.6.\n\n* I get negative line timings! What's going on?\n\n    There was a bug in 1.0b1 on Windows that resulted in this. It should be\n    fixed in 1.0b2. If you are still seeing negative numbers, please let me\n    know.\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\nIf you find a bug, or a missing feature you really want added, please post to\nthe enthought-dev_ mailing list or email the author at\n\u003crobert.kern@enthought.com\u003e.\n\n.. _enthought-dev : https://mail.enthought.com/mailman/listinfo/enthought-dev\n\n\nChanges\n=======\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\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcertik%2Fline_profiler","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcertik%2Fline_profiler","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcertik%2Fline_profiler/lists"}