无法在IPython中使用cProfile

16 投票
3 回答
6003 浏览
提问于 2025-04-15 16:31

我觉得我漏掉了一些很基础的东西。

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)')

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

NameError: name 'c' is not defined

我到底漏掉了什么呢?

更新 我会话的具体内容在这里:http://pastebin.com/f3e1b9946

更新 我之前没提到这个问题发生在IPython中,结果发现这就是问题的根源。

3 个回答

3

虽然IPython非常方便,但有时候它会导致一些罕见的情况,比如让原本能正常运行的代码出错,或者隐藏了一些错误信息。因此,当你遇到这些神秘的错误时,试着在标准的解释器中运行代码会很有帮助。

16

这不是原发帖者的问题,但如果你在__main__命名空间以外的地方调用cProfile.run(),比如在一个函数里或者通过导入的方式,也会出现这个错误。在这种情况下,你需要使用下面的代码,而不是直接用run()方法:

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

在IPython环境中,你可以使用一个叫做 %prun 魔法函数 的东西:

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}

撰写回答