代码之家  ›  专栏  ›  技术社区  ›  Boris Gorelik

无法使cProfile在IPython中工作

  •  13
  • Boris Gorelik  · 技术社区  · 15 年前

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

    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

    更新

    3 回复  |  直到 15 年前
        1
  •  26
  •   drevicko    10 年前

    在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}
    
        2
  •  16
  •   Von    14 年前

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

    荣誉 this post 谢谢你帮我解决这个问题。

        3
  •  3
  •   Denis Otkidach    15 年前

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