2009-11-30 87 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