Search code examples
pythoncprofile

Problems trying to use cProfile


I am trying to run the code below at Python 2.7 GUI:

python -m cProfile -s time abc.py

However here is the error I have:

>>> python -m cProfile -s time abc.py     
>>>                  ^
>>> SyntaxError: invalid syntax

Any idea how can I solve it?


Solution

  • You need to run this from the command line, not a GUI or the interactive Python prompt. Seeing the >>> means you are on the interactive Python prompt.

    On the command line a.k.a terminal window, change to the directory in which abc.py is located and enter:

    python -m cProfile -s time abc.py  
    

    I get this:

    python -m cProfile -s time abc.py 
             2 function calls in 0.000 seconds
    
       Ordered by: internal time
    
       ncalls  tottime  percall  cumtime  percall filename:lineno(function)
            1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
            1    0.000    0.000    0.000    0.000 abc.py:1(<module>)
    

    The option -m does this:

    -m mod : run library module as a script (terminates option list)

    The Python version is 2.7.12.

    EDIT

    If you want to do it from the interactive prompt, probably the easiest way is to use IPython or Jupyter Notebook. Then you can do this:

    [1] %run -m cProfile -s time abc.py