reversed(top()) code tags rss about

How to profile python application packaged via py2exe

February 4, 2014
[howto] [python] [programming] [profiling]

Simple profiling using standard cProfile module

Usually a command similar to the one below is used to profile an application:

python -m cProfile -o app.prof app.py arg1 arg2

The issue with packaged application

One can’t simply do this when python sources are packaged in some kind of binary container like py2exe, because in this case application is interpreted by a builtin interpreter and it’s not as easy to run profiler.

Solution

Just run profiler in code. Given something like:

# all other actions
if __name__ == '__main__':
    # main actions

Turn it into:

# all other actions

def main():
    # main actions

if __name__ == '__main__':
    cPythoh.run('main()', filename='path/to/app.prof')

Conclusion

It’s not that hard to get how to do this, but as I usually don’t profile code written in python, it took some time to get this done.