I'm profiling a Python 3.4 script within an interactive shell environment (IDE, if it matters). Normally I use cProfile
to profile functions. However, this time I have some top-level code in the script. By "top-level" I mean that the code is not inside a function definition. cProfile.run
won't accept the filename - normally I would pass it a function.
To get around this, I wrap the top-level code in a main()
function, execute it to create main
in the shell namespace, then run cProfiler.run('main()')
. This is pretty annoying - I would like to fool around with several variables generated in the top-level code, and I'd rather not try to return them all from main()
.
I have carefully read the similar questions How can you profile a python script? and How to profile my code?. They give great solutions for profiling top-level code from the command line and for profiling functions from a shell, but I don't think they address this specific question.
1 Answer 1
I have a kluge for getting this done, but I think there's probably a better way out there.
cProfile.run(compile(open(filename, "rb").read(), filename, 'exec'))
where filename
is the filename of the script.
-
I removed your disclaimer since it's not really important to answer the question. It might be better as a comment on the question.Adam Smith– Adam Smith02/06/2015 00:25:11Commented Feb 6, 2015 at 0:25
-
@AdamSmith OK, thanks - I haven't ever answered my own question before. Repeated for anyone who cares: since I've answered my own question here, I will not upvote or accept my own answer.Dave Kielpinski– Dave Kielpinski02/06/2015 01:12:03Commented Feb 6, 2015 at 1:12