在Python中分析自身及参数?

4 投票
1 回答
4987 浏览
提问于 2025-04-15 12:26

我想知道如何在Python中对一个包含self和参数的调用进行性能分析。

def performProfile(self):
    import cProfile
    self.profileCommand(1000000)

def profileCommand(self, a):
    for i in a:
        pass

在上面的例子中,我该如何只分析对profileCommand的调用呢?我发现需要用runctx来处理参数,但self该怎么处理呢?(这个代码实际上涉及到一个用户界面,所以很难单独提取出对profile的调用)。

1 个回答

13

你需要传递本地变量和全局变量的字典,并且把你通常会输入的第一个参数传进去。

cProfile.runctx("self.profileCommand(100)", globals(),locals())

可以用类似这样的方式:

class A(object):
    def performProfile(self):
        import cProfile
        cProfile.runctx("self.profileCommand(100)", globals(),locals())

    def profileCommand(self, a):
        for i in xrange(a):
            pass
        print "end."

A().performProfile()

而且不要在整个用户界面上进行性能分析,只分析特定的函数或计算。

撰写回答