14

我错过了一些非常基本的东西。

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 中,这(事实证明)是问题的根源

4

3 回答 3

26

在 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}
于 2009-11-30T17:13:48.197 回答
16

不是原始发布者的问题,但如果您在 __main__ 命名空间(从函数或导入中)以外的其他地方调用 cProfile.run() ,也会出现同样的错误。在这种情况下,您需要使用以下内容而不是 run() 方法:

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

感谢这篇文章帮助我解决了这个问题。

于 2010-07-22T03:46:58.197 回答
3

尽管 IPython 非常方便,但在极少数情况下它会破坏工作代码或掩盖错误。因此,当您遇到此类神秘错误时,在标准解释器中尝试代码很有用。

于 2009-11-30T16:56:32.093 回答