Monday, February 28, 2011

[Py] Use cProfile to check the run time performance of a program

When I was trying to figure out the usage about get_fps of pygame.time.Clock, I read about the thread:

And I noticed that they were talking about ``cProfile,'' so I went to the document about it:


During the test, I encountered the following import error:
ImportError: No module named pstats
To solve this problem, install the module named python-proflier [1], not the python-stats which I mistaken for the missing module.

Note that it seems not straightforward to run cProfile in IPython [2]. I have tried cProfile in IPython but got no expected results, so I turned to run cProfile in command line. The following example shows the command line usage of run foo.py with cProfile, and save the output into foo.profile which can be used later:
$ python -m cProfile -o foo.profile foo.py
Then run in IPython:
import pstats
p = pstats.Stats('foo.profile') # read the profile just have been saved
p.sort_stats('cumulative').print_stats(10) # sort by cumulative time, and then print the first 10 results


The output:
Mon Feb 28 17:57:59 2011    foo.profile

         57277 function calls (56161 primitive calls) in 3.940 CPU seconds

   Ordered by: cumulative time
   List reduced from 969 to 10 due to restriction <10>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    3.942    3.942 :1()
        1    0.000    0.000    3.942    3.942 {execfile}
        1    0.013    0.013    3.942    3.942 cam_pygame.py:1()
       24    0.003    0.000    2.972    0.124 cam_pygame.py:11(get_image)
       24    0.000    0.000    2.783    0.116 /usr/lib/pymodules/python2.6/opencv/highgui.py:116(cvQueryFrame)
       24    2.783    0.116    2.783    0.116 {_highgui.cvQueryFrame}
       24    0.255    0.011    0.255    0.011 {pygame.display.flip}
        1    0.067    0.067    0.154    0.154 {pygame.display.set_mode}
       24    0.145    0.006    0.145    0.006 {method 'blit' of 'pygame.Surface' objects}
        1    0.018    0.018    0.100    0.100 /usr/lib/python2.6/dist-packages/pygame/__init__.py:25()
---
Ref:
[1] "ImportError: No module named pstats" error on Ubuntu
[2] cProfile Example and iPython Magic Shortcut %prun

No comments:

Post a Comment