Last active
January 2, 2016 07:49
-
-
Save cjhanks/8272331 to your computer and use it in GitHub Desktop.
mixes callgrind with cProfile for more thorough profiling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python2 | |
| """ | |
| :author: CjHanks <develop@cjhanks.name> | |
| Usage: cvgrind module {optional_entry_point} | |
| # Will call | |
| import module | |
| # -- optionally -- | |
| module.optional_entry_point() | |
| This little snippet is used for profiling Python code which acts primarily as | |
| scripting for other applications. All subprocess calls are overloaded with | |
| valgrind profiling while the Python code is profiled using cProfile. | |
| """ | |
| import subprocess | |
| import cProfile | |
| import sys | |
| from os import remove | |
| from os.path import join | |
| from functools import partial | |
| from pstats import Stats | |
| from tempfile import NamedTemporaryFile | |
| CG_options = [ 'valgrind', '--tool=callgrind' ] | |
| def new_ACTION(old, arg, *args, **kwargs): | |
| if arg[0] == 'valgrind': | |
| return old(arg, *args, **kwargs) | |
| else: | |
| return old(CG_options + arg, *args, **kwargs) | |
| for overload in [ 'call', 'check_call', 'check_output', 'Popen' ]: | |
| setattr(subprocess, overload, partial(new_ACTION | |
| , getattr(subprocess, overload))) | |
| def main(): | |
| module_path = sys.argv[1] | |
| sys.argv = sys.argv[1:] | |
| print('-' * 80) | |
| print('START') | |
| m = __import__(module_path) | |
| print('END') | |
| output_name = NamedTemporaryFile() | |
| cProfile.run('main()', filename = output_name.name) | |
| stats = Stats(output_name.name, stream = open('python.out', 'wb')) | |
| stats.print_stats() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment