pax_global_header00006660000000000000000000000064133574103530014516gustar00rootroot0000000000000052 comment=da3d60a1b59a061a0e2113bf768b7cb4bf002ccb pprofile-2.0.2/000077500000000000000000000000001335741035300133375ustar00rootroot00000000000000pprofile-2.0.2/.gitignore000066400000000000000000000000461335741035300153270ustar00rootroot00000000000000dist/ build/ pprofile.egg-info/ *.pyc pprofile-2.0.2/.travis.yml000066400000000000000000000024241335741035300154520ustar00rootroot00000000000000sudo: false language: python python: - "2.7" - "3.6" - "pypy" - "pypy3" install: pip install . script: - pprofile --include demo --threads 0 demo/threads.py - pprofile --include demo --format callgrind demo/threads.py - pprofile --include demo --statistic .01 demo/threads.py - demo/embedded.py - pprofile --include demo demo/threads.py - pprofile --include demo demo/empty.py - pprofile --format callgrind demo/empty.py - pprofile --include demo --statistic .01 demo/empty.py - pprofile --format callgrind --zipfile source_code.zip demo/threads.py - pprofile --format callgrind --zipfile source_code.zip demo/empty.py - pprofile --exclude-syspath demo/threads.py - pprofile --exclude-syspath --statistic .01 demo/threads.py - pprofile --include demo demo/encoding.py - LC_CTYPE=ISO-8859-15 pprofile --include demo demo/encoding.py - pprofile --include demo demo/encoding.py > /dev/null - pprofile --include demo demo/empty.py -search - pprofile --include demo -- demo/empty.py -search - pprofile --include demo demo/recurse.py - pprofile --include demo demo/recurse2.py - pprofile --include demo demo/recurse3.py - pprofile --include demo demo/recurse4.py - pprofile --include demo demo/twocalls.py - pprofile --include demo demo/twocalls2.py pprofile-2.0.2/COPYING000066400000000000000000000431031335741035300143730ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. pprofile-2.0.2/MANIFEST.in000066400000000000000000000000431335741035300150720ustar00rootroot00000000000000include COPYING include README.rst pprofile-2.0.2/README.rst000066400000000000000000000460321335741035300150330ustar00rootroot00000000000000Line-granularity, thread-aware deterministic and statistic pure-python profiler Inspired from Robert Kern's line_profiler_ . Usage ===== As a command:: $ pprofile some_python_executable arg1 ... Once `some_python_executable` returns, prints annotated code of each file involved in the execution. As a command, ignoring any files from default `sys.path` (ie, python modules themselves), for shorter output:: $ pprofile --exclude-syspath some_python_executable arg1 ... Executing a module, like :code:`python -m`. `--exclude-syspath` is not recommended in this mode, as it will likely hide what you intend to profile. Also, explicitly ending pprofile arguments with `--` will prevent accidentally stealing command's arguments:: $ pprofile -m some_python_module -- arg1 ... As a module: .. code:: python import pprofile def someHotSpotCallable(): # Deterministic profiler prof = pprofile.Profile() with prof(): # Code to profile prof.print_stats() def someOtherHotSpotCallable(): # Statistic profiler prof = pprofile.StatisticalProfile() with prof( period=0.001, # Sample every 1ms single=True, # Only sample current thread ): # Code to profile prof.print_stats() For advanced usage, see :code:`pprofile --help` and :code:`pydoc pprofile`. Profiling overhead ------------------ pprofile default mode (`Deterministic profiling`_) has a large overhead. Part of the reason being that it is written to be as portable as possible (so no C extension). This large overhead can be an issue, which can be avoided by using `Statistic profiling`_ at the cost of some result readability decrease. Rule of thumb: +-----------------------------+----------------------------+------------------------+ | Code to profile runs for... | `Deterministic profiling`_ | `Statistic profiling`_ | +=============================+============================+========================+ | a few seconds | Yes | No [#]_ | +-----------------------------+----------------------------+------------------------+ | a few minutes | Maybe | Yes | +-----------------------------+----------------------------+------------------------+ | more (ex: daemon) | No | Yes [#]_ | +-----------------------------+----------------------------+------------------------+ Once you identified the hot spot and you decide you need finer-grained profiling to understand what needs fixing, you should try to make to-profile code run for shorter time so you can reasonably use deterministic profiling: use a smaller data set triggering the same code path, modify the code to only enable profiling on small pieces of code... .. [#] Statistic profiling will not have time to collect enough samples to produce usable output. .. [#] You may want to consider triggering pprofile from a signal handler or other IPC mechanism to profile a shorter subset. See `zpprofile.py` for how it can be used to profile code inside a running (zope) service (in which case the IPC mechanism is just Zope normal URL handling). Output ====== Supported output formats. Callgrind --------- The most useful output mode of pprofile is `Callgrind Profile Format`_, allows browsing profiling results with kcachegrind_ (or qcachegrind_ on Windows). :: $ pprofile --format callgrind --out cachegrind.out.threads demo/threads.py Callgrind format is implicitly enabled if ``--out`` basename starts with ``cachegrind.out.``, so above command can be simplified as:: $ pprofile --out cachegrind.out.threads demo/threads.py If you are analyzing callgrind traces on a different machine, you may want to use the ``--zipfile`` option to generate a zip file containing all files:: $ pprofile --out cachegrind.out.threads --zipfile threads_source.zip demo/threads.py Generated files will use relative paths, so you can extract generated archive in the same path as profiling result, and kcachegrind will load them - and not your system-wide files, which may differ. Annotated code -------------- Human-readable output, but can become difficult to use with large programs. :: $ pprofile demo/threads.py Profiling modes =============== Deterministic profiling ----------------------- In deterministic profiling mode, pprofile gets notified of each executed line. This mode generates very detailed reports, but at the cost of a large overhead. Also, profiling hooks being per-thread, either profiling must be enable before spawning threads (if you want to profile more than just the current thread), or profiled application must provide ways of enabling profiling afterwards - which is not very convenient. :: $ pprofile --threads 0 demo/threads.py Command line: ['demo/threads.py'] Total duration: 1.00573s File: demo/threads.py File duration: 1.00168s (99.60%) Line #| Hits| Time| Time per hit| %|Source code ------+----------+-------------+-------------+-------+----------- 1| 2| 3.21865e-05| 1.60933e-05| 0.00%|import threading 2| 1| 5.96046e-06| 5.96046e-06| 0.00%|import time 3| 0| 0| 0| 0.00%| 4| 2| 1.5974e-05| 7.98702e-06| 0.00%|def func(): 5| 1| 1.00111| 1.00111| 99.54%| time.sleep(1) 6| 0| 0| 0| 0.00%| 7| 2| 2.00272e-05| 1.00136e-05| 0.00%|def func2(): 8| 1| 1.69277e-05| 1.69277e-05| 0.00%| pass 9| 0| 0| 0| 0.00%| 10| 1| 1.81198e-05| 1.81198e-05| 0.00%|t1 = threading.Thread(target=func) (call)| 1| 0.000610828| 0.000610828| 0.06%|# /usr/lib/python2.7/threading.py:436 __init__ 11| 1| 1.52588e-05| 1.52588e-05| 0.00%|t2 = threading.Thread(target=func) (call)| 1| 0.000438929| 0.000438929| 0.04%|# /usr/lib/python2.7/threading.py:436 __init__ 12| 1| 4.79221e-05| 4.79221e-05| 0.00%|t1.start() (call)| 1| 0.000843048| 0.000843048| 0.08%|# /usr/lib/python2.7/threading.py:485 start 13| 1| 6.48499e-05| 6.48499e-05| 0.01%|t2.start() (call)| 1| 0.00115609| 0.00115609| 0.11%|# /usr/lib/python2.7/threading.py:485 start 14| 1| 0.000205994| 0.000205994| 0.02%|(func(), func2()) (call)| 1| 1.00112| 1.00112| 99.54%|# demo/threads.py:4 func (call)| 1| 3.09944e-05| 3.09944e-05| 0.00%|# demo/threads.py:7 func2 15| 1| 7.62939e-05| 7.62939e-05| 0.01%|t1.join() (call)| 1| 0.000423908| 0.000423908| 0.04%|# /usr/lib/python2.7/threading.py:653 join 16| 1| 5.26905e-05| 5.26905e-05| 0.01%|t2.join() (call)| 1| 0.000320196| 0.000320196| 0.03%|# /usr/lib/python2.7/threading.py:653 join Note that time.sleep call is not counted as such. For some reason, python is not generating c_call/c_return/c_exception events (which are ignored by current code, as a result). Statistic profiling ------------------- In statistic profiling mode, pprofile periodically snapshots the current callstack(s) of current process to see what is being executed. As a result, profiler overhead can be dramatically reduced, making it possible to profile real workloads. Also, as statistic profiling acts at the whole-process level, it can be toggled independently of profiled code. The downside of statistic profiling is that output lacks timing information, which makes it harder to understand. :: $ pprofile --statistic .01 demo/threads.py Command line: ['demo/threads.py'] Total duration: 1.0026s File: demo/threads.py File duration: 0s (0.00%) Line #| Hits| Time| Time per hit| %|Source code ------+----------+-------------+-------------+-------+----------- 1| 0| 0| 0| 0.00%|import threading 2| 0| 0| 0| 0.00%|import time 3| 0| 0| 0| 0.00%| 4| 0| 0| 0| 0.00%|def func(): 5| 288| 0| 0| 0.00%| time.sleep(1) 6| 0| 0| 0| 0.00%| 7| 0| 0| 0| 0.00%|def func2(): 8| 0| 0| 0| 0.00%| pass 9| 0| 0| 0| 0.00%| 10| 0| 0| 0| 0.00%|t1 = threading.Thread(target=func) 11| 0| 0| 0| 0.00%|t2 = threading.Thread(target=func) 12| 0| 0| 0| 0.00%|t1.start() 13| 0| 0| 0| 0.00%|t2.start() 14| 0| 0| 0| 0.00%|(func(), func2()) (call)| 96| 0| 0| 0.00%|# demo/threads.py:4 func 15| 0| 0| 0| 0.00%|t1.join() 16| 0| 0| 0| 0.00%|t2.join() File: /usr/lib/python2.7/threading.py File duration: 0s (0.00%) Line #| Hits| Time| Time per hit| %|Source code ------+----------+-------------+-------------+-------+----------- [...] 308| 0| 0| 0| 0.00%| def wait(self, timeout=None): [...] 338| 0| 0| 0| 0.00%| if timeout is None: 339| 1| 0| 0| 0.00%| waiter.acquire() 340| 0| 0| 0| 0.00%| if __debug__: [...] 600| 0| 0| 0| 0.00%| def wait(self, timeout=None): [...] 617| 0| 0| 0| 0.00%| if not self.__flag: 618| 0| 0| 0| 0.00%| self.__cond.wait(timeout) (call)| 1| 0| 0| 0.00%|# /usr/lib/python2.7/threading.py:308 wait [...] 724| 0| 0| 0| 0.00%| def start(self): [...] 748| 0| 0| 0| 0.00%| self.__started.wait() (call)| 1| 0| 0| 0.00%|# /usr/lib/python2.7/threading.py:600 wait 749| 0| 0| 0| 0.00%| 750| 0| 0| 0| 0.00%| def run(self): [...] 760| 0| 0| 0| 0.00%| if self.__target: 761| 0| 0| 0| 0.00%| self.__target(*self.__args, **self.__kwargs) (call)| 192| 0| 0| 0.00%|# demo/threads.py:4 func 762| 0| 0| 0| 0.00%| finally: [...] 767| 0| 0| 0| 0.00%| def __bootstrap(self): [...] 780| 0| 0| 0| 0.00%| try: 781| 0| 0| 0| 0.00%| self.__bootstrap_inner() (call)| 192| 0| 0| 0.00%|# /usr/lib/python2.7/threading.py:790 __bootstrap_inner [...] 790| 0| 0| 0| 0.00%| def __bootstrap_inner(self): [...] 807| 0| 0| 0| 0.00%| try: 808| 0| 0| 0| 0.00%| self.run() (call)| 192| 0| 0| 0.00%|# /usr/lib/python2.7/threading.py:750 run Some details are lost (not all executed lines have a non-null hit-count), but the hot spot is still easily identifiable in this trivial example, and its call stack is still visible. Thread-aware profiling ====================== ``ThreadProfile`` class provides the same features as ``Profile``, but uses ``threading.settrace`` to propagate tracing to ``threading.Thread`` threads started after profiling is enabled. Limitations ----------- The time spent in another thread is not discounted from interrupted line. On the long run, it should not be a problem if switches are evenly distributed among lines, but threads executing fewer lines will appear as eating more CPU time than they really do. This is not specific to simultaneous multi-thread profiling: profiling a single thread of a multi-threaded application will also be polluted by time spent in other threads. Example (lines are reported as taking longer to execute when profiled along with another thread - although the other thread is not profiled):: $ demo/embedded.py Total duration: 1.00013s File: demo/embedded.py File duration: 1.00003s (99.99%) Line #| Hits| Time| Time per hit| %|Source code ------+----------+-------------+-------------+-------+----------- 1| 0| 0| 0| 0.00%|#!/usr/bin/env python 2| 0| 0| 0| 0.00%|import threading 3| 0| 0| 0| 0.00%|import pprofile 4| 0| 0| 0| 0.00%|import time 5| 0| 0| 0| 0.00%|import sys 6| 0| 0| 0| 0.00%| 7| 1| 1.5974e-05| 1.5974e-05| 0.00%|def func(): 8| 0| 0| 0| 0.00%| # Busy loop, so context switches happen 9| 1| 1.40667e-05| 1.40667e-05| 0.00%| end = time.time() + 1 10| 146604| 0.511392| 3.48826e-06| 51.13%| while time.time() < end: 11| 146603| 0.48861| 3.33288e-06| 48.85%| pass 12| 0| 0| 0| 0.00%| 13| 0| 0| 0| 0.00%|# Single-treaded run 14| 0| 0| 0| 0.00%|prof = pprofile.Profile() 15| 0| 0| 0| 0.00%|with prof: 16| 0| 0| 0| 0.00%| func() (call)| 1| 1.00003| 1.00003| 99.99%|# ./demo/embedded.py:7 func 17| 0| 0| 0| 0.00%|prof.annotate(sys.stdout, __file__) 18| 0| 0| 0| 0.00%| 19| 0| 0| 0| 0.00%|# Dual-threaded run 20| 0| 0| 0| 0.00%|t1 = threading.Thread(target=func) 21| 0| 0| 0| 0.00%|prof = pprofile.Profile() 22| 0| 0| 0| 0.00%|with prof: 23| 0| 0| 0| 0.00%| t1.start() 24| 0| 0| 0| 0.00%| func() 25| 0| 0| 0| 0.00%| t1.join() 26| 0| 0| 0| 0.00%|prof.annotate(sys.stdout, __file__) Total duration: 1.00129s File: demo/embedded.py File duration: 1.00004s (99.88%) Line #| Hits| Time| Time per hit| %|Source code ------+----------+-------------+-------------+-------+----------- [...] 7| 1| 1.50204e-05| 1.50204e-05| 0.00%|def func(): 8| 0| 0| 0| 0.00%| # Busy loop, so context switches happen 9| 1| 2.38419e-05| 2.38419e-05| 0.00%| end = time.time() + 1 10| 64598| 0.538571| 8.33728e-06| 53.79%| while time.time() < end: 11| 64597| 0.461432| 7.14324e-06| 46.08%| pass [...] This also means that the sum of the percentage of all lines can exceed 100%. It can reach the number of concurrent threads (200% with 2 threads being busy for the whole profiled execution time, etc). Example with 3 threads:: $ pprofile demo/threads.py Command line: ['demo/threads.py'] Total duration: 1.00798s File: demo/threads.py File duration: 3.00604s (298.22%) Line #| Hits| Time| Time per hit| %|Source code ------+----------+-------------+-------------+-------+----------- 1| 2| 3.21865e-05| 1.60933e-05| 0.00%|import threading 2| 1| 6.91414e-06| 6.91414e-06| 0.00%|import time 3| 0| 0| 0| 0.00%| 4| 4| 3.91006e-05| 9.77516e-06| 0.00%|def func(): 5| 3| 3.00539| 1.0018|298.16%| time.sleep(1) 6| 0| 0| 0| 0.00%| 7| 2| 2.31266e-05| 1.15633e-05| 0.00%|def func2(): 8| 1| 2.38419e-05| 2.38419e-05| 0.00%| pass 9| 0| 0| 0| 0.00%| 10| 1| 1.81198e-05| 1.81198e-05| 0.00%|t1 = threading.Thread(target=func) (call)| 1| 0.000612974| 0.000612974| 0.06%|# /usr/lib/python2.7/threading.py:436 __init__ 11| 1| 1.57356e-05| 1.57356e-05| 0.00%|t2 = threading.Thread(target=func) (call)| 1| 0.000438213| 0.000438213| 0.04%|# /usr/lib/python2.7/threading.py:436 __init__ 12| 1| 6.60419e-05| 6.60419e-05| 0.01%|t1.start() (call)| 1| 0.000913858| 0.000913858| 0.09%|# /usr/lib/python2.7/threading.py:485 start 13| 1| 6.8903e-05| 6.8903e-05| 0.01%|t2.start() (call)| 1| 0.00167513| 0.00167513| 0.17%|# /usr/lib/python2.7/threading.py:485 start 14| 1| 0.000200272| 0.000200272| 0.02%|(func(), func2()) (call)| 1| 1.00274| 1.00274| 99.48%|# demo/threads.py:4 func (call)| 1| 4.19617e-05| 4.19617e-05| 0.00%|# demo/threads.py:7 func2 15| 1| 9.58443e-05| 9.58443e-05| 0.01%|t1.join() (call)| 1| 0.000411987| 0.000411987| 0.04%|# /usr/lib/python2.7/threading.py:653 join 16| 1| 5.29289e-05| 5.29289e-05| 0.01%|t2.join() (call)| 1| 0.000316143| 0.000316143| 0.03%|# /usr/lib/python2.7/threading.py:653 join Note that the call time is not added to file total: it's already accounted for inside "func". Why another profiler ? ====================== Python's standard profiling tools have a callable-level granularity, which means it is only possible to tell which function is a hot-spot, not which lines in that function. Robert Kern's line_profiler_ is a very nice alternative providing line-level profiling granularity, but in my opinion it has a few drawbacks which (in addition to the attractive technical challenge) made me start pprofile: - It is not pure-python. This choice makes sense for performance but makes usage with pypy difficult and requires installation (I value execution straight from checkout). - It requires source code modification to select what should be profiled. I prefer to have the option to do an in-depth, non-intrusive profiling. - As an effect of previous point, it does not have a notion above individual callable, annotating functions but not whole files - preventing module import profiling. - Profiling recursive code provides unexpected results (recursion cost is accumulated on callable's first line) because it doesn't track call stack. This may be unintended, and may be fixed at some point in line_profiler. .. _line_profiler: https://github.com/rkern/line_profiler .. _`Callgrind Profile Format`: http://valgrind.org/docs/manual/cl-format.html .. _kcachegrind: http://kcachegrind.sourceforge.net .. _qcachegrind: http://sourceforge.net/projects/qcachegrindwin/ pprofile-2.0.2/demo/000077500000000000000000000000001335741035300142635ustar00rootroot00000000000000pprofile-2.0.2/demo/embedded.py000077500000000000000000000007141335741035300163730ustar00rootroot00000000000000#!/usr/bin/env python import threading import pprofile import time import sys def func(): # Busy loop, so context switches happen end = time.time() + 1 while time.time() < end: pass # Single-treaded run prof = pprofile.Profile() with prof: func() prof.annotate(sys.stdout, __file__) # Dual-threaded run t1 = threading.Thread(target=func) prof = pprofile.Profile() with prof: t1.start() func() t1.join() prof.annotate(sys.stdout, __file__) pprofile-2.0.2/demo/empty.py000066400000000000000000000000001335741035300157610ustar00rootroot00000000000000pprofile-2.0.2/demo/encoding.py000066400000000000000000000001061335741035300164200ustar00rootroot00000000000000#!/usr/bin/env python import iso_8859_1 import utf_8 import utf_8_bom pprofile-2.0.2/demo/exceptions.py000066400000000000000000000006541335741035300170230ustar00rootroot00000000000000#!/usr/bin/env python def trigger(): raise Exception def indirect(): trigger() # Caught exception try: raise Exception except Exception: pass # Caught exception, from function try: trigger() except Exception: pass # Caught exception, from deeper function try: indirect() except Exception: pass # Uncaught exception, from function try: trigger() finally: pass print 'Never reached' pprofile-2.0.2/demo/iso_8859_1.py000066400000000000000000000001441335741035300163430ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: ISO-8859-1 -*- # This is an iso-8859-1 "e" with acute accent: é pprofile-2.0.2/demo/recurse.py000066400000000000000000000001671335741035300163110ustar00rootroot00000000000000from time import sleep MAX_LEVEL = 10 def foo(level=0): if level < MAX_LEVEL: foo(level + 1) sleep(0.01) foo() pprofile-2.0.2/demo/recurse2.py000066400000000000000000000002241335741035300163650ustar00rootroot00000000000000from time import sleep MAX_LEVEL = 10 def boo(level=0): if level < MAX_LEVEL: baz(level + 1) sleep(0.01) def baz(level): boo(level) boo() pprofile-2.0.2/demo/recurse3.py000066400000000000000000000002111335741035300163620ustar00rootroot00000000000000from time import sleep MAX_LEVEL = 5 def bar(level=0): if level < MAX_LEVEL: bar(level + 1) bar(level + 1) sleep(0.01) bar() pprofile-2.0.2/demo/recurse4.py000066400000000000000000000002341335741035300163700ustar00rootroot00000000000000from time import sleep MAX_LEVEL = 5 def bar(level=0): if level < MAX_LEVEL: bar(level + 1) bar(level + 1) bar(level + 1) sleep(0.01) bar() pprofile-2.0.2/demo/threads.py000077500000000000000000000003501335741035300162700ustar00rootroot00000000000000#!/usr/bin/env python import threading import time def func(): time.sleep(1) def func2(): pass t1 = threading.Thread(target=func) t2 = threading.Thread(target=func) t1.start() t2.start() (func(), func2()) t1.join() t2.join() pprofile-2.0.2/demo/twocalls.py000066400000000000000000000001501335741035300164610ustar00rootroot00000000000000from time import sleep def bar(): sleep(0.1) def baz(): sleep(0.1) def foo(): bar() baz() foo() pprofile-2.0.2/demo/twocalls2.py000066400000000000000000000001201335741035300165400ustar00rootroot00000000000000from time import sleep def bar(): sleep(0.1) def foo(): bar() bar() foo() pprofile-2.0.2/demo/utf_8.py000066400000000000000000000001331335741035300156570ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: UTF-8 -*- # This is an utf-8 "e" with acute accent: é pprofile-2.0.2/demo/utf_8_bom.py000066400000000000000000000001061335741035300165140ustar00rootroot00000000000000#!/usr/bin/env python # This is an utf-8 "e" with acute accent: é pprofile-2.0.2/pprofile.py000077500000000000000000001441231335741035300155410ustar00rootroot00000000000000#!/usr/bin/env python # Copyright (C) 2013-2018 Vincent Pelletier # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ pprofile - Line-granularity, thread-aware deterministic and statistic pure-python profiler Usage as a command line: $ pprofile --exclude-syspath some_python_executable arg1 ... $ pprofile --exclude-syspath -m some_python_module -- arg1 ... $ python -m pprofile --exclude-syspath some_python_executable arg1 ... $ python -m pprofile -m some_python_module -- arg1 ... See --help for all options. Usage as a python module: Deterministic profiling: >>> prof = pprofile.Profile() >>> with prof(): >>> # Code to profile >>> prof.print_stats() Statistic profiling: >>> prof = StatisticalProfile() >>> with prof(): >>> # Code to profile >>> prof.print_stats() """ from __future__ import print_function, division from collections import defaultdict, deque from functools import partial, wraps # Note: use time, not clock. # Clock, at least on linux, ignores time not spent executing code # (ex: time.sleep()). The goal of pprofile is not to profile python code # execution as such (ie, to improve python interpreter), but to profile a # possibly complex application, with its (IO) waits, sleeps, (...) so a # developper can understand what is slow rather than what keeps the cpu busy. # So using the wall-clock as a way to measure time spent is more meaningful. # XXX: This said, if time() lacks precision, a better but likely # platform-dependent wall-clock time source must be identified and used. from time import time from warnings import warn import argparse import io import inspect from itertools import count import linecache import os # not caught by 2to3, likely because pipes.quote is not documented in python 2 try: from pipes import quote as shlex_quote # Python 2 except ImportError: from shlex import quote as shlex_quote # Python 3 import platform import re import runpy import shlex from subprocess import list2cmdline as windows_list2cmdline import sys import threading import zipfile try: from IPython.core.magic import register_line_cell_magic except ImportError: register_line_cell_magic = lambda x: x __all__ = ( 'ProfileBase', 'ProfileRunnerBase', 'Profile', 'ThreadProfile', 'StatisticProfile', 'StatisticThread', 'run', 'runctx', 'runfile', 'runpath', ) class BaseLineIterator(object): def __init__(self, getline, filename, global_dict): self._getline = getline self._filename = filename self._global_dict = global_dict self._lineno = 1 def __iter__(self): return self def next(self): lineno = self._lineno self._lineno += 1 return lineno, self._getline(self._filename, lineno, self._global_dict) if sys.version_info < (3, ): import codecs # Find coding specification (see PEP-0263) _matchCoding = re.compile( r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)', ).match class LineIterator(BaseLineIterator): _encoding = None def __init__(self, *args, **kw): super(LineIterator, self).__init__(*args, **kw) # Identify encoding. first_line = self._getline(self._filename, 1, self._global_dict) if isinstance(first_line, bytes): # BOM - python2 only detects the (discouraged) UTF-8 BOM if first_line.startswith(codecs.BOM_UTF8): self._encoding = 'utf-8' else: # PEP-0263: "the first or second line must match [_matchCoding]" match = _matchCoding(first_line) if match is None: match = _matchCoding( self._getline(self._filename, 2, self._global_dict), ) if match is None: self._encoding = 'ascii' else: self._encoding = match.group(1) # else, first line is unicode. def next(self): lineno, line = super(LineIterator, self).next() if self._encoding: line = line.decode(self._encoding, errors='replace') return lineno, line else: # getline returns unicode objects, nothing to do LineIterator = BaseLineIterator if platform.system() == 'Windows': quoteCommandline = windows_list2cmdline else: def quoteCommandline(commandline): return ' '.join(shlex_quote(x) for x in commandline) class EncodeOrReplaceWriter(object): """ Write-only file-ish object which replaces unsupported chars when underlying file rejects them. """ def __init__(self, out): self._encoding = getattr(out, 'encoding', None) or 'ascii' self._write = out.write def write(self, data): try: self._write(data) except UnicodeEncodeError: self._write( data.encode( self._encoding, errors='replace', ).decode(self._encoding), ) def _isCallgrindName(filepath): return os.path.basename(filepath).startswith('cachegrind.out.') class _FileTiming(object): """ Accumulation of profiling statistics (line and call durations) for a given source "file" (unique global dict). Subclasses should be aware that: - this classes uses __slots__, mainly for cpu efficiency (property lookup is in a list instead of a dict) - it can access the BaseProfile instance which created any instace using the "profiler" property, should they share some state across source files. - methods on this class are profiling choke-point - keep customisations as cheap in CPU as you can ! """ __slots__ = ('line_dict', 'call_dict', 'filename', 'global_dict', 'profiler') def __init__(self, filename, global_dict, profiler): self.filename = filename self.global_dict = global_dict self.line_dict = defaultdict(lambda: defaultdict(lambda: [0, 0])) self.call_dict = {} # Note: not used in this implementation, may be used by subclasses. self.profiler = profiler def hit(self, code, line, duration): """ A line has finished executing. code (code) container function's code object line (int) line number of just executed line duration (float) duration of the line, in seconds """ entry = self.line_dict[line][code] entry[0] += 1 entry[1] += duration def call(self, code, line, callee_file_timing, callee, duration, frame): """ A call originating from this file returned. code (code) caller's code object line (int) caller's line number callee_file_timing (FileTiming) callee's FileTiming callee (code) callee's code object duration (float) duration of the call, in seconds frame (frame) calle's entire frame as of its return """ try: entry = self.call_dict[(code, line, callee)] except KeyError: self.call_dict[(code, line, callee)] = [callee_file_timing, 1, duration] else: entry[1] += 1 entry[2] += duration def getHitStatsFor(self, line): total_hits = total_duration = 0 for hits, duration in self.line_dict.get(line, {}).itervalues(): total_hits += hits total_duration += duration return total_hits, total_duration def getLastLine(self): return max( max(self.line_dict) if self.line_dict else 0, max(x for _, x, _ in self.call_dict) if self.call_dict else 0, ) def iterHits(self): for line, code_dict in self.line_dict.iteritems(): for code, (hits, duration) in code_dict.iteritems(): yield line, code, hits, duration def iterCalls(self): for (code, line, callee), (callee_file_timing, hit, duration) in \ self.call_dict.iteritems(): yield ( line, code, hit, duration, callee_file_timing.filename, callee, ) def getCallListByLine(self): result = defaultdict(list) for line, code, hit, duration, callee_filename, callee in self.iterCalls(): result[line].append(( code, hit, duration, callee_filename, callee, )) return result def getTotalTime(self): return sum( y[1] for x in self.line_dict.itervalues() for y in x.itervalues() ) def getTotalHitCount(self): return sum( y[0] for x in self.line_dict.itervalues() for y in x.itervalues() ) def getSortKey(self): # total duration first, then total hit count for statistical profiling result = [0, 0] for entry in self.line_dict.itervalues(): for hit, duration in entry.itervalues(): result[0] += duration result[1] += hit return result FileTiming = _FileTiming class LocalDescriptor(threading.local): """ Implementation of descriptor API for thread-local properties. """ def __init__(self, func=None): """ func (callable) If provided, called when a missing property is accessed (ex: accessing thread never initialised that property). If None, AttributeError is raised. """ super(LocalDescriptor, self).__init__() if func is not None: self.func = func def __get__(self, instance, owner): try: return getattr(self, str(id(instance))) except AttributeError: # Raises AttributeError if func was not provided. value = self.func() setattr(self, str(id(instance)), value) return value def __set__(self, instance, value): setattr(self, str(id(instance)), value) def __delete__(self, instance): try: delattr(self, str(id(instance))) except AttributeError: pass _ANNOTATE_HEADER = \ u'%6s|%10s|' \ u'%13s|%13s|%7s|' \ u'Source code' % ( u'Line #', u'Hits', u'Time', u'Time per hit', u'%', ) _ANNOTATE_HORIZONTAL_LINE = u''.join(x == u'|' and u'+' or u'-' for x in _ANNOTATE_HEADER) _ANNOTATE_FORMAT = \ u'%(lineno)6i|%(hits)10i|' \ u'%(time)13g|%(time_per_hit)13g|%(percent)6.2f%%|' \ u'%(line)s' _ANNOTATE_CALL_FORMAT = \ u'(call)|%(hits)10i|' \ u'%(time)13g|%(time_per_hit)13g|%(percent)6.2f%%|' \ u'# %(callee_file)s:%(callee_line)s %(callee_name)s' def _initStack(): # frame_time: when current frame execution started/resumed last # frame_discount: time discounted from current frame, because it appeared # lower in the call stack from the same callsite # lineno: latest line which execution started # line_time: time at which latest line started being executed # line_duration: total time spent in current line up to last resume now = time() return (deque([[now, 0, None, now, 0]]), defaultdict(deque)) def _verboseProfileDecorator(self): def decorator(func): @wraps(func) def wrapper(frame, event, arg): self._traceEvent(frame, event) return func(frame, event, arg) return wrapper return decorator class ProfileBase(object): """ Methods common to deterministic and statistic profiling. Subclasses can override the "FileTiming" property to use a different class. """ __slots__ = ( 'file_dict', 'global_dict', 'total_time', '__dict__', '__weakref__', 'merged_file_dict', ) FileTiming = _FileTiming def __init__(self): self.file_dict = {} self.merged_file_dict = {} self.global_dict = {} self.total_time = 0 def _getFileTiming(self, frame): try: return self.global_dict[id(frame.f_globals)] except KeyError: f_globals = frame.f_globals name = self._getFilename(frame) self.global_dict[id(frame.f_globals)] = file_timing = self.FileTiming( name, f_globals, self, ) # file_dict modifications must be thread-safe to not lose measures. # setdefault is atomic, append is atomic. self.file_dict.setdefault(name, []).append(file_timing) return file_timing @staticmethod def _getFilename(frame): """ Overload in subclasses to customise filename generation. """ return frame.f_code.co_filename @staticmethod def _getline(filename, lineno, global_dict): """ Overload in subclasses to customise source retrieval. """ return linecache.getline(filename, lineno, global_dict) def _mergeFileTiming(self, rebuild=False): merged_file_dict = self.merged_file_dict if merged_file_dict and not rebuild: return merged_file_dict merged_file_dict.clear() # Regroup by module, to find all duplicates from other threads. by_global_dict = defaultdict(list) for file_timing_list in self.file_dict.itervalues(): for file_timing in file_timing_list: by_global_dict[ id(file_timing.global_dict) ].append( file_timing, ) # Resolve name conflicts. global_to_named_dict = {} for global_dict_id, file_timing_list in by_global_dict.iteritems(): file_timing = file_timing_list[0] name = file_timing.filename if name in merged_file_dict: counter = count() base_name = name while name in merged_file_dict: name = base_name + '_%i' % next(counter) global_to_named_dict[global_dict_id] = merged_file_dict[name] = FileTiming( name, file_timing.global_dict, file_timing.profiler, # Note: should be self ) # Add all file timings from one module together under its # deduplicated name. This needs to happen after all names # are generated and all empty file timings are created so # call events cross-references can be remapped. for merged_file_timing in merged_file_dict.itervalues(): line_dict = merged_file_timing.line_dict for file_timing in by_global_dict[id(merged_file_timing.global_dict)]: for line, other_code_dict in file_timing.line_dict.iteritems(): code_dict = line_dict[line] for code, ( other_hits, other_duration, ) in other_code_dict.iteritems(): entry = code_dict[code] entry[0] += other_hits entry[1] += other_duration call_dict = merged_file_timing.call_dict for key, ( other_callee_file_timing, other_hits, other_duration, ) in file_timing.call_dict.iteritems(): try: entry = call_dict[key] except KeyError: entry = call_dict[key] = [ global_to_named_dict[ id(other_callee_file_timing.global_dict) ], other_hits, other_duration, ] else: entry[1] += other_hits entry[2] += other_duration return merged_file_dict def getFilenameSet(self): """ Returns a set of profiled file names. Note: "file name" is used loosely here. See python documentation for co_filename, linecache module and PEP302. It may not be a valid filesystem path. """ result = set(self._mergeFileTiming()) # Ignore profiling code. __file__ does not always provide consistent # results with f_code.co_filename (ex: easy_install with zipped egg), # so inspect current frame instead. # Get current file from one of pprofile methods. Compatible with # implementations that do not have the inspect.currentframe() method # (e.g. IronPython). # XXX: Assumes that all of pprofile code is in a single file. # XXX: Assumes that _initStack exists in pprofile module. result.discard(inspect.getsourcefile(_initStack)) return result def _getFileNameList(self, filename, may_sort=True): if filename is None: filename = self.getFilenameSet() elif isinstance(filename, basestring): return [filename] if may_sort: try: # Detect if filename is an ordered data type. filename[:0] except TypeError: # Not ordered, sort. file_dict = self._mergeFileTiming() filename = sorted(filename, reverse=True, key=lambda x: file_dict[x].getSortKey() ) return filename def callgrind(self, out, filename=None, commandline=None, relative_path=False): """ Dump statistics in callgrind format. Contains: - per-line hit count, time and time-per-hit - call associations (call tree) Note: hit count is not inclusive, in that it is not the sum of all hits inside that call. Time unit: microsecond (1e-6 second). out (file-ish opened for writing) Destination of callgrind profiling data. filename (str, collection of str) If provided, dump stats for given source file(s) only. By default, list for all known files. commandline (anything with __str__) If provided, will be output as the command line used to generate this profiling data. relative_path (bool) When True, absolute elements are stripped from path. Useful when maintaining several copies of source trees with their own profiling result, so kcachegrind does not look in system-wide files which may not match with profiled code. """ print(u'# callgrind format', file=out) print(u'version: 1', file=out) print(u'creator: pprofile', file=out) print(u'event: usphit :microseconds/hit', file=out) print(u'events: hits microseconds usphit', file=out) if commandline is not None: print(u'cmd:', commandline, file=out) file_dict = self._mergeFileTiming() if relative_path: convertPath = _relpath else: convertPath = lambda x: x if os.path.sep != "/": # qCacheGrind (windows build) needs at least one UNIX separator # in path to find the file. Adapt here even if this is probably # more of a qCacheGrind issue... convertPath = lambda x, cascade=convertPath: cascade( '/'.join(x.split(os.path.sep)) ) code_to_name_dict = {} homonym_counter = {} def getCodeName(filename, code): # Tracks code objects globally, because callee information needs # to be consistent accross files. # Inside a file, grants unique names to each code object. try: return code_to_name_dict[code] except KeyError: name = code.co_name + ':%i' % code.co_firstlineno key = (filename, name) homonym_count = homonym_counter.get(key, 0) if homonym_count: name += '_%i' % homonym_count homonym_counter[key] = homonym_count + 1 code_to_name_dict[code] = name return name for current_file in self._getFileNameList(filename, may_sort=False): file_timing = file_dict[current_file] print(u'fl=%s' % convertPath(current_file), file=out) # When a local callable is created an immediately executed, this # loop would start a new "fn=" section but would not end it before # emitting "cfn=" lines, making the callee appear as not being # called by interrupted "fn=" section. # So dispatch all functions in a first pass, and build # uninterrupted sections in a second pass. # Note: cost line is a list just to be mutable. A single item is # expected. func_dict = defaultdict(lambda: defaultdict(lambda: ([], []))) for lineno, code, hits, duration in file_timing.iterHits(): func_dict[getCodeName(current_file, code)][lineno][0].append( (hits, int(duration * 1000000)), ) for ( lineno, caller, call_hits, call_duration, callee_file, callee, ) in file_timing.iterCalls(): call_ticks = int(call_duration * 1000000) func_call_list = func_dict[ getCodeName(current_file, caller) ][lineno][1] append = func_call_list.append append(u'cfl=' + convertPath(callee_file)) append(u'cfn=' + getCodeName(callee_file, callee)) append(u'calls=%i %i' % (call_hits, callee.co_firstlineno)) append(u'%i %i %i %i' % (lineno, call_hits, call_ticks, call_ticks // call_hits)) for func_name, line_dict in func_dict.iteritems(): print(u'fn=%s' % func_name, file=out) for lineno, (func_hit_list, func_call_list) in sorted(line_dict.iteritems()): if func_hit_list: # Multiple function objects may "reside" on the same # line of the same file (same global dict). # Sum these up and produce a single cachegrind event. hits = sum(x for x, _ in func_hit_list) ticks = sum(x for _, x in func_hit_list) print( u'%i %i %i %i' % ( lineno, hits, ticks, ticks // hits, ), file=out, ) for line in func_call_list: print(line, file=out) def annotate(self, out, filename=None, commandline=None, relative_path=False): """ Dump annotated source code with current profiling statistics to "out" file. Time unit: second. out (file-ish opened for writing) Destination of annotated sources. filename (str, collection of str) If provided, dump stats for given source file(s) only. If unordered collection, it will get sorted by decreasing total file score (total time if available, then total hit count). By default, list for all known files. commandline (anything with __str__) If provided, will be output as the command line used to generate this annotation. relative_path (bool) For compatibility with callgrind. Ignored. """ file_dict = self._mergeFileTiming() total_time = self.total_time if commandline is not None: print(u'Command line:', commandline, file=out) print(u'Total duration: %gs' % total_time, file=out) if not total_time: return def percent(value, scale): if scale == 0: return 0 return value * 100 / scale for name in self._getFileNameList(filename): file_timing = file_dict[name] file_total_time = file_timing.getTotalTime() call_list_by_line = file_timing.getCallListByLine() print(u'File: %s' % name, file=out) print(u'File duration: %gs (%.2f%%)' % (file_total_time, percent(file_total_time, total_time)), file=out) print(_ANNOTATE_HEADER, file=out) print(_ANNOTATE_HORIZONTAL_LINE, file=out) last_line = file_timing.getLastLine() for lineno, line in LineIterator( self._getline, file_timing.filename, file_timing.global_dict, ): if not line and lineno > last_line: break hits, duration = file_timing.getHitStatsFor(lineno) print(_ANNOTATE_FORMAT % { u'lineno': lineno, u'hits': hits, u'time': duration, u'time_per_hit': duration / hits if hits else 0, u'percent': percent(duration, total_time), u'line': (line or u'').rstrip(), }, file=out) for ( _, call_hits, call_duration, callee_file, callee, ) in call_list_by_line.get(lineno, ()): print(_ANNOTATE_CALL_FORMAT % { u'hits': call_hits, u'time': call_duration, u'time_per_hit': call_duration / call_hits, u'percent': percent(call_duration, total_time), u'callee_file': callee_file, u'callee_line': callee.co_firstlineno, u'callee_name': callee.co_name, }, file=out) def _iterRawFile(self, name): file_timing = self._mergeFileTiming()[name] for lineno in count(1): line = self._getline(file_timing.filename, lineno, file_timing.global_dict) if not line: break yield line def iterSource(self): """ Iterator over all involved files. Yields 2-tuple composed of file path and an iterator over (non-annotated) source lines. Can be used to generate a file tree for use with kcachegrind, for example. """ for name in self.getFilenameSet(): yield name, self._iterRawFile(name) # profile/cProfile-like API def dump_stats(self, filename): """ Similar to profile.Profile.dump_stats - but different output format ! """ if _isCallgrindName(filename): with open(filename, 'w') as out: self.callgrind(out) else: with io.open(filename, 'w', errors='replace') as out: self.annotate(out) def print_stats(self): """ Similar to profile.Profile.print_stats . Returns None. """ self.annotate(EncodeOrReplaceWriter(sys.stdout)) class ProfileRunnerBase(object): def __call__(self): return self def __enter__(self): raise NotImplementedError def __exit__(self, exc_type, exc_val, exc_tb): raise NotImplementedError # profile/cProfile-like API def runctx(self, cmd, globals, locals): """Similar to profile.Profile.runctx .""" with self(): exec(cmd, globals, locals) return self def runcall(self, func, *args, **kw): """Similar to profile.Profile.runcall .""" with self(): return func(*args, **kw) def runfile(self, fd, argv, fd_name='', compile_flags=0, dont_inherit=1, globals={}): with fd: code = compile(fd.read(), fd_name, 'exec', flags=compile_flags, dont_inherit=dont_inherit) original_sys_argv = list(sys.argv) ctx_globals = globals.copy() ctx_globals['__file__'] = fd_name ctx_globals['__name__'] = '__main__' ctx_globals['__package__'] = None try: sys.argv[:] = argv return self.runctx(code, ctx_globals, None) finally: sys.argv[:] = original_sys_argv def runpath(self, path, argv): original_sys_path = list(sys.path) try: sys.path.insert(0, os.path.dirname(path)) return self.runfile(open(path, 'rb'), argv, fd_name=path) finally: sys.path[:] = original_sys_path def runmodule(self, module, argv): original_sys_argv = list(sys.argv) original_sys_path0 = sys.path[0] try: sys.path[0] = os.getcwd() sys.argv[:] = argv with self(): runpy.run_module(module, run_name='__main__', alter_sys=True) finally: sys.argv[:] = original_sys_argv sys.path[0] = original_sys_path0 return self class Profile(ProfileBase, ProfileRunnerBase): """ Deterministic, recursive, line-granularity, profiling class. Does not require any source code change to work. If the performance hit is too large, it can benefit from some integration (calling enable/disable around selected code chunks). The sum of time spent in all profiled lines is less than the total profiled time reported. This is (part of) profiling overhead. This also mans that sum of time-spent-on-line percentage is less than 100%. All times are "internal time", ie they do not count time spent inside called (profilable, so python) functions. """ __slots__ = ( '_global_trace', '_local_trace', 'stack', 'enabled_start', ) def __init__(self, verbose=False): super(Profile, self).__init__() if verbose: self._global_trace = _verboseProfileDecorator(self)( self._real_global_trace) self._local_trace = _verboseProfileDecorator(self)( self._real_local_trace) else: self._global_trace = self._real_global_trace self._local_trace = self._real_local_trace self.stack = None self.enabled_start = None def _enable(self): """ Overload this method when subclassing. Called before actually enabling trace. """ self.stack = _initStack() self.enabled_start = time() def enable(self): """ Enable profiling. """ if self.enabled_start: warn('Duplicate "enable" call') else: self._enable() sys.settrace(self._global_trace) def _disable(self): """ Overload this method when subclassing. Called after actually disabling trace. """ self.total_time += time() - self.enabled_start self.enabled_start = None del self.stack def disable(self): """ Disable profiling. """ if self.enabled_start: sys.settrace(None) self._disable() else: warn('Duplicate "disable" call') def __enter__(self): """ __enter__() -> self """ self.enable() return self def __exit__(self, exc_type, exc_val, exc_tb): """ __exit__(*excinfo) -> None. Disables profiling. """ self.disable() def _traceEvent(self, frame, event): f_code = frame.f_code lineno = frame.f_lineno print('%10.6f%s%s %s:%s %s+%s' % ( time() - self.enabled_start, ' ' * len(self.stack[0]), event, f_code.co_filename, lineno, f_code.co_name, lineno - f_code.co_firstlineno, ), file=sys.stderr) def _real_global_trace(self, frame, event, arg): local_trace = self._local_trace if local_trace is not None: event_time = time() callee_entry = [event_time, 0, frame.f_lineno, event_time, 0] stack, callee_dict = self.stack try: caller_entry = stack[-1] except IndexError: pass else: # Suspend caller frame frame_time, frame_discount, lineno, line_time, line_duration = caller_entry caller_entry[4] = event_time - line_time + line_duration callee_dict[(frame.f_back.f_code, frame.f_code)].append(callee_entry) stack.append(callee_entry) return local_trace def _real_local_trace(self, frame, event, arg): if event == 'line' or event == 'return': event_time = time() stack, callee_dict = self.stack try: stack_entry = stack[-1] except IndexError: warn('Profiling stack underflow, disabling.') self.disable() return None frame_time, frame_discount, lineno, line_time, line_duration = stack_entry file_timing = self._getFileTiming(frame) file_timing.hit(frame.f_code, lineno, event_time - line_time + line_duration) if event == 'line': # Start a new line stack_entry[2] = frame.f_lineno stack_entry[3] = event_time stack_entry[4] = 0 else: # 'return' event, is still callee # Resume caller frame stack.pop() stack[-1][3] = event_time caller_frame = frame.f_back caller_code = caller_frame.f_code callee_code = frame.f_code callee_entry_list = callee_dict[(caller_code, callee_code)] callee_entry_list.pop() call_duration = event_time - frame_time if callee_entry_list: # Callee is also somewhere up the stack, so discount this # call duration from it. callee_entry_list[-1][1] += call_duration self._getFileTiming(caller_frame).call( caller_code, caller_frame.f_lineno, file_timing, callee_code, call_duration - frame_discount, frame, ) return self._local_trace # profile/cProfile-like API def run(self, cmd): """Similar to profile.Profile.run .""" import __main__ dikt = __main__.__dict__ return self.runctx(cmd, dikt, dikt) class ThreadProfile(Profile): """ threading.Thread-aware version of Profile class. Threads started after enable() call will be profiled. After disable() call, threads will need to be switched into and trigger a trace event (typically a "line" event) before they can notice the disabling. """ __slots__ = ('_local_trace_backup', ) stack = LocalDescriptor(_initStack) global_dict = LocalDescriptor(dict) def __init__(self, **kw): super(ThreadProfile, self).__init__(**kw) self._local_trace_backup = self._local_trace def _enable(self): self._local_trace = self._local_trace_backup threading.settrace(self._global_trace) super(ThreadProfile, self)._enable() def _disable(self): super(ThreadProfile, self)._disable() threading.settrace(None) self._local_trace = None class StatisticProfile(ProfileBase, ProfileRunnerBase): """ Statistic profiling class. This class does not gather its own samples by itself. Instead, it must be provided with call stacks (as returned by sys._getframe() or sys._current_frames()). """ def __init__(self): super(StatisticProfile, self).__init__() self.total_time = 1 def sample(self, frame): getFileTiming = self._getFileTiming called_timing = getFileTiming(frame) called_code = frame.f_code called_timing.hit(called_code, frame.f_lineno, 0) while True: caller = frame.f_back if caller is None: break caller_timing = getFileTiming(caller) caller_code = caller.f_code caller_timing.call(caller_code, caller.f_lineno, called_timing, called_code, 0, frame) called_timing = caller_timing frame = caller called_code = caller_code def __call__(self, period=.001, single=True, group=None, name=None): """ Instanciate StatisticThread. >>> s_profile = StatisticProfile() >>> with s_profile(single=False): >>> # Code to profile Is equivalent to: >>> s_profile = StatisticProfile() >>> s_thread = StatisticThread(profiler=s_profile, single=False) >>> with s_thread: >>> # Code to profile """ return StatisticThread( profiler=self, period=period, single=single, group=group, name=name, ) # BBB StatisticalProfile = StatisticProfile class StatisticThread(threading.Thread, ProfileRunnerBase): """ Usage in a nutshell: with StatisticThread() as profiler_thread: # do stuff profiler_thread.profiler.print_stats() """ __slots__ = ( '_test', '_start_time', 'clean_exit', ) def __init__(self, profiler=None, period=.001, single=True, group=None, name=None): """ profiler (None or StatisticProfile instance) Available on instances as the "profiler" read-only property. If None, a new profiler instance will be created. period (float) How many seconds to wait between consecutive samples. The smaller, the more profiling overhead, but the faster results become meaningful. The larger, the less profiling overhead, but requires long profiling session to get meaningful results. single (bool) Profile only the thread which created this instance. group, name See Python's threading.Thread API. """ if profiler is None: profiler = StatisticProfile() if single: self._test = lambda x, ident=threading.current_thread().ident: ident == x else: self._test = None super(StatisticThread, self).__init__( group=group, name=name, ) self._stop_event = threading.Event() self._period = period self._profiler = profiler profiler.total_time = 0 self.daemon = True self.clean_exit = False @property def profiler(self): return self._profiler def start(self): self.clean_exit = False self._can_run = True self._start_time = time() super(StatisticThread, self).start() def stop(self): """ Request thread to stop. Does not wait for actual termination (use join() method). """ if self.is_alive(): self._can_run = False self._stop_event.set() self._profiler.total_time += time() - self._start_time self._start_time = None def __enter__(self): """ __enter__() -> self """ self.start() return self def __exit__(self, exc_type, exc_val, exc_tb): """ __exit__(*excinfo) -> None. Stops and joins profiling thread. """ self.stop() self.join() def run(self): current_frames = sys._current_frames test = self._test if test is None: test = lambda x, ident=threading.current_thread().ident: ident != x sample = self._profiler.sample stop_event = self._stop_event wait = partial(stop_event.wait, self._period) while self._can_run: for ident, frame in current_frames().iteritems(): if test(ident): sample(frame) frame = None wait() stop_event.clear() self.clean_exit = True def callgrind(self, *args, **kw): warn('deprecated', DeprecationWarning) return self._profiler.callgrind(*args, **kw) def annotate(self, *args, **kw): warn('deprecated', DeprecationWarning) return self._profiler.annotate(*args, **kw) def dump_stats(self, *args, **kw): warn('deprecated', DeprecationWarning) return self._profiler.dump_stats(*args, **kw) def print_stats(self, *args, **kw): warn('deprecated', DeprecationWarning) return self._profiler.print_stats(*args, **kw) def iterSource(self, *args, **kw): warn('deprecated', DeprecationWarning) return self._profiler.iterSource(*args, **kw) # BBB StatisticalThread = StatisticThread # profile/cProfile-like API (no sort parameter !) def _run(threads, verbose, func_name, filename, *args, **kw): if threads: klass = ThreadProfile else: klass = Profile prof = klass(verbose=verbose) try: try: getattr(prof, func_name)(*args, **kw) except SystemExit: pass finally: if filename is None: prof.print_stats() else: prof.dump_stats(filename) def run(cmd, filename=None, threads=True, verbose=False): """Similar to profile.run .""" _run(threads, verbose, 'run', filename, cmd) def runctx(cmd, globals, locals, filename=None, threads=True, verbose=False): """Similar to profile.runctx .""" _run(threads, verbose, 'runctx', filename, cmd, globals, locals) def runfile(fd, argv, fd_name='', compile_flags=0, dont_inherit=1, filename=None, threads=True, verbose=False): """ Run code from given file descriptor with profiling enabled. Closes fd before executing contained code. """ _run(threads, verbose, 'runfile', filename, fd, argv, fd_name, compile_flags, dont_inherit) def runpath(path, argv, filename=None, threads=True, verbose=False): """ Run code from open-accessible file path with profiling enabled. """ _run(threads, verbose, 'runpath', filename, path, argv) _allsep = os.sep + (os.altsep or '') def _relpath(name): """ Strip absolute components from path. Inspired from zipfile.write(). """ return os.path.normpath(os.path.splitdrive(name)[1]).lstrip(_allsep) def _main(argv, stdin=None): format_dict = { 'text': 'annotate', 'callgrind': 'callgrind', } parser = argparse.ArgumentParser(argv[0]) parser.add_argument('script', help='Python script to execute (optionaly ' 'followed by its arguments)', nargs='?') parser.add_argument('argv', nargs=argparse.REMAINDER) parser.add_argument('-o', '--out', default='-', help='Write annotated sources to this file. Defaults to stdout.') parser.add_argument('-z', '--zipfile', help='Name of a zip file to generate from all involved source files. ' 'Useful with callgrind output.') parser.add_argument('-t', '--threads', default=1, type=int, help='If ' 'non-zero, trace threads spawned by program. Default: %(default)s') parser.add_argument('-f', '--format', choices=format_dict, help='Format in which output is generated. If not set, auto-detected ' 'from filename if provided, falling back to "text".') parser.add_argument('-v', '--verbose', action='store_true', help='Enable profiler internal tracing output. Cryptic and verbose.') parser.add_argument('-s', '--statistic', default=0, type=float, help='Use this period for statistic profiling, or use deterministic ' 'profiling when 0.') parser.add_argument('-m', dest='module', help='Searches sys.path for the named module and runs the ' 'corresponding .py file as a script. When given, positional arguments ' 'become sys.argv[1:]') group = parser.add_argument_group( title='Filtering', description='Allows excluding (and re-including) code from ' '"file names" matching regular expressions. ' '"file name" follows the semantics of python\'s "co_filename": ' 'it may be a valid path, of an existing or non-existing file, ' 'but it may be some arbitrary string too.' ) group.add_argument('--exclude-syspath', action='store_true', help='Exclude all from default "sys.path". Beware: this will also ' 'exclude properly-installed non-standard modules, which may not be ' 'what you want.') group.add_argument('--exclude', action='append', default=[], help='Exclude files whose name starts with any pattern.') group.add_argument('--include', action='append', default=[], help='Include files whose name would have otherwise excluded. ' 'If no exclusion was specified, all paths are excluded first.') options = parser.parse_args(argv[1:]) if options.exclude_syspath: options.exclude.extend('^' + re.escape(x) for x in sys.path) if options.include and not options.exclude: options.exclude.append('') # All-matching regex if options.verbose: if options.exclude: print('Excluding:', file=sys.stderr) for regex in options.exclude: print('\t' + regex, file=sys.stderr) if options.include: print('But including:', file=sys.stderr) for regex in options.include: print('\t' + regex, file=sys.stderr) if options.module is None: if options.script is None: parser.error('too few arguments') args = [options.script] + options.argv runner_method_kw = { 'path': args[0], 'argv': args, } runner_method_id = 'runpath' elif stdin is not None and options.module == '-': # Undocumented way of using -m, used internaly by %%pprofile args = [''] if options.script is not None: args.append(options.script) args.extend(options.argv) import __main__ runner_method_kw = { 'fd': stdin, 'argv': args, 'fd_name': '', 'globals': __main__.__dict__, } runner_method_id = 'runfile' else: args = [options.module] if options.script is not None: args.append(options.script) args.extend(options.argv) runner_method_kw = { 'module': options.module, 'argv': args, } runner_method_id = 'runmodule' if options.format is None: if _isCallgrindName(options.out): options.format = 'callgrind' else: options.format = 'text' relative_path = options.format == 'callgrind' and options.zipfile if options.statistic: prof = StatisticalProfile() runner = StatisticalThread( profiler=prof, period=options.statistic, single=not options.threads, ) else: if options.threads: klass = ThreadProfile else: klass = Profile prof = runner = klass(verbose=options.verbose) try: getattr(runner, runner_method_id)(**runner_method_kw) finally: if options.out == '-': out = EncodeOrReplaceWriter(sys.stdout) close = lambda: None else: out = io.open(options.out, 'w', errors='replace') close = out.close if options.exclude: exclusion_search_list = [ re.compile(x).search for x in options.exclude ] include_search_list = [ re.compile(x).search for x in options.include ] filename_set = { x for x in prof.getFilenameSet() if not ( any(y(x) for y in exclusion_search_list) and not any(y(x) for y in include_search_list) ) } else: filename_set = None commandline = quoteCommandline(args) getattr(prof, format_dict[options.format])( out, filename=filename_set, # python2 repr returns bytes, python3 repr returns unicode commandline=getattr( commandline, 'decode', lambda _: commandline, )('ascii'), relative_path=relative_path, ) close() zip_path = options.zipfile if zip_path: if relative_path: convertPath = _relpath else: convertPath = lambda x: x with zipfile.ZipFile( zip_path, mode='w', compression=zipfile.ZIP_DEFLATED, ) as zip_file: for name, lines in prof.iterSource(): zip_file.writestr( convertPath(name), ''.join(lines) ) if options.statistic and not runner.clean_exit: # Mostly useful for regresion testing, as exceptions raised in threads # do not change exit status. sys.exit(1) def pprofile(line, cell=None): """ Profile line execution. """ if cell is None: # TODO: detect and use arguments (statistical profiling, ...) ? return run(line) return _main( ['%%pprofile', '-m', '-'] + shlex.split(line), io.StringIO(cell), ) try: register_line_cell_magic(pprofile) except Exception: # ipython can be imported, but may not be currently running. pass del pprofile def main(): _main(sys.argv) if __name__ == '__main__': main() pprofile-2.0.2/setup.py000066400000000000000000000037711335741035300150610ustar00rootroot00000000000000#!/usr/bin/env python # Copyright (C) 2013-2018 Vincent Pelletier # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from os.path import join, dirname import sys from setuptools import setup description = open(join(dirname(__file__), 'README.rst')).read() setup( name='pprofile', version='2.0.2', author='Vincent Pelletier', author_email='plr.vincent@gmail.com', description=next(x for x in description.splitlines() if x.strip()), long_description='.. contents::\n\n' + description, url='http://github.com/vpelletier/pprofile', license='GPL 2+', platforms=['any'], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: Implementation :: PyPy', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: IronPython', 'Topic :: Software Development', ], py_modules=['pprofile', 'zpprofile'], entry_points={ 'console_scripts': [ 'pprofile=pprofile:main', ], }, zip_safe=True, use_2to3=sys.version_info >= (3, ), ) pprofile-2.0.2/zpprofile.py000066400000000000000000000520631335741035300157310ustar00rootroot00000000000000# Copyright (C) 2016-2018 Vincent Pelletier # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ Zope-friendly layer for pprofile. In Zope: - Executed code is not necessarily a valid FS path (ex: Python Scripts) - Executed code is not available to the machine where profiling results are analysed. - Restricted Python cannot manipulate all desired types, and one may want to trigger profiling from its level. This layer addresses all these issues, by making interesting pprofile classes accessible to restricted python and bundling source code wxith profiling results. NOTE: This does allow anyone able to get profiler output to get whole source files from your server. So better keep good track of who can profile and/or where profiling results end. Alone, this module won't be accessible from Restricted Python. Example deterministic usage: # Get profiler (how you get to zpprofile module depends on your # application). profiler = zpprofile.getProfiler() # Get callable (to not profile how it is retrieved). func = context.somethingOrOther # Actually profile stuff with profiler: func() # Build response response = context.REQUEST.RESPONSE data, content_type = profiler.asZip() response.setHeader('content-type', content_type) response.setHeader( 'content-disposition', 'attachment; filename="' + func.id + '.zip"', ) # Push response immediately (hopefully, profiled function did not write # anything on its own). response.write(data) # Make transaction fail, so any otherwise persistent change made by # profiled function is undone - note that many caches will still have # been warmed up, just as with any other code. raise Exception('profiling') Example statistic usage (to profile other running threads): from time import sleep # Get profiler (how you get to zpprofile module depends on your # application). profiler, thread = zpprofile.getStatisticalProfilerAndThread(single=False) # Actually profile whatever is going on in the same process, just waiting. with thread: sleep(60) # Build response response = context.REQUEST.RESPONSE data, content_type = profiler.asZip() response.setHeader('content-type', content_type) response.setHeader( 'content-disposition', 'attachment; filename="statistical_' + DateTime().strftime('%Y%m%d%H%M%S') + '.zip"', ) return data """ from __future__ import print_function import dis from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.encoders import encode_quopri import functools import gc from io import StringIO, BytesIO from importlib import import_module import itertools import os from collections import defaultdict import zipfile import pprofile def getFuncCodeOrNone(module, attribute_path): try: value = import_module(module) for attribute in attribute_path: value = getattr(value, attribute) value = value.func_code except (ImportError, AttributeError): print('Could not reach func_code of module %r, attribute path %r' % (module, attribute_path)) return None return value DB_query_func_code = getFuncCodeOrNone('Products.ZMySQLDA.db', ('DB', '_query')) ZODB_setstate_func_code = getFuncCodeOrNone('ZODB.Connection', ('Connection', '_setstate')) PythonExpr__call__func_code = getFuncCodeOrNone('zope.tales.pythonexpr', ('PythonExpr', '__call__')) ZRPythonExpr__call__func_code = getFuncCodeOrNone('Products.PageTemplates.ZRPythonExpr', ('PythonExpr', '__call__')) DT_UtilEvaleval_func_code = getFuncCodeOrNone('DocumentTemplate.DT_Util', ('Eval', 'eval')) SharedDCScriptsBindings_bindAndExec_func_code = getFuncCodeOrNone('Shared.DC.Scripts.Bindings', ('Bindings', '_bindAndExec')) PythonScript_exec_func_code = getFuncCodeOrNone('Products.PythonScripts.PythonScript', ('PythonScript', '_exec')) # OFS.Traversable.Traversable.unrestrictedTraverse overwites its path argument, # preventing post-invocation introspection. As it does not mutate the argument, # it is still possible to inspect using such controlled intermediate function. def unrestrictedTraverse_spy(self, path, *args, **kw): return orig_unrestrictedTraverse(self, path, *args, **kw) unrestrictedTraverse_spy_func_code = unrestrictedTraverse_spy.func_code try: import OFS.Traversable orig_unrestrictedTraverse = OFS.Traversable.Traversable.unrestrictedTraverse except (ImportError, AttributeError): pass else: functools.update_wrapper(unrestrictedTraverse_spy, orig_unrestrictedTraverse) OFS.Traversable.Traversable.unrestrictedTraverse = unrestrictedTraverse_spy _ALLSEP = os.sep + (os.altsep or '') PYTHON_EXPR_FUNC_CODE_SET = (ZRPythonExpr__call__func_code, PythonExpr__call__func_code) class ZopeFileTiming(pprofile.FileTiming): def call(self, code, line, callee_file_timing, callee, duration, frame): f_code = frame.f_code if f_code is DB_query_func_code: self.profiler.sql_dict[frame.f_locals['query']].append(duration) elif f_code is ZODB_setstate_func_code: f_locals = frame.f_locals obj = f_locals['obj'] try: oid = obj._p_oid except AttributeError: pass else: self.profiler.zodb_dict[ f_locals['self'].db().database_name ][oid].append(duration) elif f_code is unrestrictedTraverse_spy_func_code: f_locals = frame.f_locals self.profiler.traverse_dict[ (repr(f_locals['self']), repr(f_locals['path'])) ].append(duration) super(ZopeFileTiming, self).call( code, line, callee_file_timing, callee, duration, frame, ) def tabulate(title_list, row_list): # de-lazify row_list = list(row_list) column_count = len(title_list) max_width_list = [len(x) for x in title_list] for row in row_list: assert len(row) == column_count, repr(row) for index, value in enumerate(row): max_width_list[index] = max(max_width_list[index], len(unicode(value))) format_string = u''.join(u'| %%-%is ' % x for x in max_width_list) + u'|\n' out = StringIO() write = out.write write(format_string % tuple(title_list)) write(u''.join(u'+' + (u'-' * (x + 2)) for x in max_width_list) + u'+\n') for row in row_list: write(format_string % tuple(row)) return out.getvalue() def disassemble(co, lasti=-1): """Disassemble a code object.""" # Taken from dis.disassemble, returns disassembled code instead of printing # it (the fuck python ?). # Also, unicodified. # Also, use % operator instead of string operations. # Also, one statement per line. out = StringIO() code = co.co_code labels = dis.findlabels(code) linestarts = dict(dis.findlinestarts(co)) n = len(code) i = 0 extended_arg = 0 free = None while i < n: c = code[i] op = ord(c) if i in linestarts: if i > 0: print(end=u'\n', file=out) print(u'%3d' % linestarts[i], end=u' ', file=out) else: print(u' ', end=u' ', file=out) if i == lasti: print(u'-->', end=u' ', file=out) else: print(u' ', end=u' ', file=out) if i in labels: print(u'>>', end=u' ', file=out) else: print(u' ', end=u' ', file=out) print(u'%4i' % i, end=u' ', file=out) print(u'%-20s' % dis.opname[op], end=u' ', file=out) i = i + 1 if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i + 1]) * 256 + extended_arg extended_arg = 0 i = i + 2 if op == dis.EXTENDED_ARG: extended_arg = oparg * 65536 print(u'%5i' % oparg, end=u' ', file=out) if op in dis.hasconst: print(u'(%r)' % co.co_consts[oparg], end=u' ', file=out) elif op in dis.hasname: print(u'(%s)' % co.co_names[oparg], end=u' ', file=out) elif op in dis.hasjrel: print(u'(to %r)' % (i + oparg), end=u' ', file=out) elif op in dis.haslocal: print(u'(%s)' % co.co_varnames[oparg], end=u' ', file=out) elif op in dis.hascompare: print(u'(%s)' % dis.cmp_op[oparg], end=u' ', file=out) elif op in dis.hasfree: if free is None: free = co.co_cellvars + co.co_freevars print(u'(%s)' % free[oparg], end=u' ', file=out) print(end=u'\n', file=out) return out.getvalue() class ZopeMixIn(object): virtual__slots__ = ( 'sql_dict', 'zodb_dict', 'fake_source_dict', 'traverse_dict', 'anonymous_module_global_dict', ) __allow_access_to_unprotected_subobjects__ = 1 FileTiming = ZopeFileTiming def __init__(self): super(ZopeMixIn, self).__init__() self.sql_dict = defaultdict(list) self.zodb_dict = defaultdict(lambda: defaultdict(list)) self.fake_source_dict = {} self.traverse_dict = defaultdict(list) self.anonymous_module_global_dict = {} def _enable(self): gc.disable() super(ZopeMixIn, self)._enable() def _disable(self): super(ZopeMixIn, self)._disable() gc.enable() def _getline(self, filename, lineno, global_dict): line_list = self.fake_source_dict.get(filename) if line_list is None: return super(ZopeMixIn, self)._getline( filename, lineno, global_dict, ) assert lineno > 0 try: return line_list[lineno - 1] except IndexError: return '' def _rememberFile(self, source, suggested_name, extension): filename = suggested_name setdefault = self.fake_source_dict.setdefault suffix = itertools.count() source = source.splitlines(True) while setdefault(filename + extension, source) != source: filename = suggested_name + '_%i' % next(suffix) return filename + extension def _getFilename(self, frame): parent_frame = frame.f_back # Some frame in our stack may contain this frame's source. # Or maybe it was in the stak at some point but not anymore # (ex: callback). # Lookup is not by function code, as there can be local functions # inside a source-less "module". As globals are shared within a # module, follow these instead. # Also, these local functions can be called at call stack depths # unrelated to the code responsible for their existence, further # complicating the search. Hopefully it should be rare enough to # keep overhead reasonable. frame_globals = frame.f_globals # Maybe we already investigated these globals ? # Returns a 2-tuple: filename, frame_globals. frame_globals are # included just to prevent their accidental re-use by an unrelated # module-ish. # We rely on code not willingly reusing globals between modules-ish. # This mapping allows finding source when it is not in the stack # anymore (callback). result = self.anonymous_module_global_dict.get(id(frame_globals)) if result is not None: return result[0] while parent_frame is not None: parent_code = parent_frame.f_code parent_locals = parent_frame.f_locals if parent_code is PythonScript_exec_func_code and parent_locals.get('g') is frame_globals: python_script = parent_locals['self'] filename = self._rememberFile( python_script.body().decode('utf-8'), python_script.id, '.py', ) self.anonymous_module_global_dict[id(frame_globals)] = ( filename, frame_globals, ) return filename if parent_code is DT_UtilEvaleval_func_code and parent_locals.get('d') is frame_globals: filename = self._rememberFile( parent_locals['self'].expr.decode('utf-8'), 'DT_Util_Eval', '.py', ) self.anonymous_module_global_dict[id(frame_globals)] = ( filename, frame_globals, ) return filename if parent_code in PYTHON_EXPR_FUNC_CODE_SET and parent_locals.get('vars') is frame_globals: source = parent_locals['self'].text if not isinstance(source, unicode): source = source.decode('utf-8') filename = self._rememberFile( source, 'PythonExpr', '.py', ) self.anonymous_module_global_dict[id(frame_globals)] = ( filename, frame_globals, ) return filename parent_frame = parent_frame.f_back # Shared.DC.Scripts preamble is directly called by _bindAndExec. # Put after stack recursion because, although simpler, this code # will rarely match, while many Python Scripts, DT and Python # Expressions are expected and often found at the first iteration. if parent_frame is not None and parent_frame.f_code is SharedDCScriptsBindings_bindAndExec_func_code: return self._rememberFile( u'# This is an auto-generated preamble executed by ' u'Shared.DC.Scripts.Bindings before "actual" code.\n' + disassemble(frame.f_code), 'preamble', '.py.bytecode', ) # The answer was not in the stack. Maybe it filename is actually fine ? # This is tested late in case linecache was patched super_self = super(ZopeMixIn, self) filename = super_self._getFilename(frame) if super_self._getline(filename, 1, frame_globals): return filename # Could not find source, provide disassembled bytecode as last resort. return self._rememberFile( u'# Unidentified source for ' + filename + '\n' + disassemble( frame.f_code, ), '%s.%s' % (filename, frame.f_code.co_name), '.py.bytecode', ) def _iterOutFiles(self): """ Yields path, data, mimetype for each file involved on or produced by profiling. """ out = StringIO() self.callgrind(out, relative_path=True) yield ( 'cachegrind.out.pprofile', out.getvalue(), 'application/x-kcachegrind', ) for name, lines in self.iterSource(): lines = ''.join(lines) if lines: if isinstance(lines, unicode): lines = lines.encode('utf-8') yield ( os.path.normpath( os.path.splitdrive(name)[1] ).lstrip(_ALLSEP), lines, 'text/x-python', ) sql_name_template = 'query_%%0%ii-%%i_hits_%%6fs.sql' % len( str(len(self.sql_dict)), ) for index, (query, time_list) in enumerate( sorted( self.sql_dict.iteritems(), key=lambda x: (sum(x[1]), len(x[1])), reverse=True, ), ): yield ( sql_name_template % ( index, len(time_list), sum(time_list), ), b'\n'.join(b'-- %10.6fs' % x for x in time_list) + b'\n' + query, 'application/sql', ) if self.zodb_dict: yield ( 'ZODB_setstate.txt', '\n\n'.join( ( '%s (%fs)\n' % ( db_name, sum(sum(x) for x in oid_dict.itervalues()), ) ) + '\n'.join( '%s (%i): %s' % ( oid.encode('hex'), len(time_list), ', '.join('%fs' % x for x in time_list), ) for oid, time_list in oid_dict.iteritems() ) for db_name, oid_dict in self.zodb_dict.iteritems() ), 'text/plain', ) if self.traverse_dict: yield ( 'unrestrictedTraverse_pathlist.txt', tabulate( ('self', 'path', 'hit', 'total duration'), sorted( ( (context, path, len(duration_list), sum(duration_list)) for (context, path), duration_list in self.traverse_dict.iteritems() ), key=lambda x: x[3], reverse=True, ), ), 'text/plain', ) def asMIMEString(self): """ Return a mime-multipart representation of: - callgrind profiling statistics (cachegrind.out.pprofile) - any SQL query issued via ZMySQLDA (query_*.sql) - any persistent object load via ZODB.Connection (ZODB_setstate.txt) - any path argument given to unrestrictedTraverse (unrestrictedTraverse_pathlist.txt) - all involved python code, including Python Scripts without hierarchy (the rest) To unpack resulting file, see "unpack a MIME message" in http://docs.python.org/2/library/email-examples.html Or get demultipart from https://pypi.python.org/pypi/demultipart """ result = MIMEMultipart() base_type_dict = { 'application': MIMEApplication, 'text': MIMEText, } encoder_dict = { 'application/x-kcachegrind': encode_quopri, 'text/x-python': 'utf-8', 'text/plain': 'utf-8', } for path, data, mimetype in self._iterOutFiles(): base_type, sub_type = mimetype.split('/') chunk = base_type_dict[base_type]( data, sub_type, encoder_dict.get(mimetype), ) chunk.add_header( 'Content-Disposition', 'attachment', filename=path, ) result.attach(chunk) return result.as_string(), result['content-type'] def asZip(self): """ Return a serialised zip archive containing: - callgrind profiling statistics (cachegrind.out.pprofile) - any SQL query issued via ZMySQLDA (query_*.sql) - any persistent object load via ZODB.Connection (ZODB_setstate.txt) - any path argument given to unrestrictedTraverse (unrestrictedTraverse_pathlist.txt) - all involved python code, including Python Scripts without hierarchy (the rest) """ out = BytesIO() with zipfile.ZipFile( out, mode='w', compression=zipfile.ZIP_DEFLATED, ) as outfile: for path, data, _ in self._iterOutFiles(): outfile.writestr(path, data) return out.getvalue(), 'application/zip' class ZopeProfiler(ZopeMixIn, pprofile.Profile): __slots__ = ZopeMixIn.virtual__slots__ class ZopeStatisticalProfile(ZopeMixIn, pprofile.StatisticalProfile): __slots__ = ZopeMixIn.virtual__slots__ class ZopeStatisticalThread(pprofile.StatisticalThread): __allow_access_to_unprotected_subobjects__ = 1 # Intercept "verbose" parameter to prevent writing to stdout. def getProfiler(verbose=False, **kw): """ Get a Zope-friendly pprofile.Profile instance. """ return ZopeProfiler(**kw) def getStatisticalProfilerAndThread(**kw): """ Get Zope-friendly pprofile.StatisticalProfile and pprofile.StatisticalThread instances. Arguments are forwarded to StatisticalThread.__init__ . """ profiler = ZopeStatisticalProfile() return profiler, ZopeStatisticalThread( profiler=profiler, **kw )