无法使cProfile在IPython中工作

Bor*_*lik 13 python profiler profiling ipython

我遗漏了一些非常基本的东西.

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)')
Run Code Online (Sandbox Code Playgroud)

当我在IPython中运行上面的代码时,我得到:

NameError: name 'c' is not defined
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

更新我的会话的确切粘贴在这里:http://pastebin.com/f3e1b9946

更新我没有提到问题出现在IPython中,(事实证明)是问题的根源

unu*_*tbu 26

在IPython中,你可以使用%prun magic函数:

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}
Run Code Online (Sandbox Code Playgroud)


Von*_*Von 15

不是原始海报的问题,但是如果你在__main__命名空间以外的某个东西(从函数或导入中)调用cProfile.run(),你也会得到同样的错误.在这种情况下,您需要使用以下代替run()方法:

cProfile.runctx("your code", globals(), locals())
Run Code Online (Sandbox Code Playgroud)

荣誉对这篇文章帮助我弄清楚了这一点.