2009-11-30 24 views
12

我很想念一些非常基本的东西。无法使cProfile在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)') 

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

NameError: name 'c' is not defined 

我缺少什么?

UPDATE我会议的确切贴在这里:http://pastebin.com/f3e1b9946

UPDATE我没有提到,在IPython中,这(在原来)是问题

的源发生问题

回答

24

虽然里面IPython中,你可以使用%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} 
+0

哇,太棒了!我不知道%prun :) – 2011-02-18 02:42:41

+0

'%prun魔术功能'的死链接,我还没有找到它应该更新到什么。 – retracile 2011-07-13 17:35:44

+1

@retracile:谢谢你的提醒。链接固定。 – unutbu 2011-07-13 17:37:58

3

虽然IPython非常方便,但它有很多罕见的情况,当它打破工作代码或掩码错误。所以当你遇到这样的神秘错误时,在标准解释器中尝试代码是很有用的。

15

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

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

荣誉给this post帮助我弄清楚了这一点。

+0

啊!获胜者,我简直不敢相信没有编辑我的代码的情况下无法在shell中进行配置。 – 2010-08-11 00:40:08