Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot make cProfile work in IPython

I'm missing something very basic.

class C:
    def __init__(self):
        self.N = 100
        pass

    def f(self, param):
        print 'C.f -- param'
        for k in xrange(param):
            for i in xrange(self.N):
                for j in xrange(self.N):
                    a = float(i)/(1+float(j)) + float(i/self.N) ** float(j/self.N)

import cProfile

c = C()
cProfile.run('c.f(3)')

When I run the above code in IPython, I get:

NameError: name 'c' is not defined

What am I missing?

UPDATE the exact paste of my session is here: http://pastebin.com/f3e1b9946

UPDATE I didn't mention that the problem occurs in IPython, which (at it turns out) is the source of the problem

like image 451
Boris Gorelik Avatar asked Nov 30 '09 12:11

Boris Gorelik


People also ask

How do you use cProfile in Python?

The syntax is cProfile. run(statement, filename=None, sort=-1) . You can pass python code or a function name that you want to profile as a string to the statement argument. If you want to save the output in a file, it can be passed to the filename argument.

Which tool will Analyse the data collected by the Python profiler?

Analysis of the profiler data is done using the Stats class. This class constructor creates an instance of a “statistics object” from a filename (or list of filenames) or from a Profile instance.


2 Answers

While inside IPython, you can use the %prun magic function:

In [9]: %prun c.f(3)
C.f -- param
         3 function calls in 0.066 CPU seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.066    0.066    0.066    0.066 <string>:6(f)
        1    0.000    0.000    0.066    0.066 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
like image 68
unutbu Avatar answered Oct 16 '22 07:10

unutbu


Not the original poster's problem, but you can also get this same error if you are invoking cProfile.run() in something other than the __main__ namespace (from within a function or an import). In that case you need to use the following instead of the run() method:

cProfile.runctx("your code", globals(), locals())

Kudos to this post for helping me figure this out.

like image 24
Von Avatar answered Oct 16 '22 07:10

Von