使用Python的timeit模块

#file B
class B:
    def printargs(self, a, b):
        print a, b


#file A
from B import B
class A:
    def somemethod(self):
        from timeit import Timer
        from functools import partial
        foo = B()
        t = Timer(partial(foo.printargs, 1, 2))


#test file
from A import A
if __name__==’__main__’:A().somemethod()

 

某些情况下

from Foo import Foo
if __name__ == '__main__':
...
   foo = Foo(arg1, arg2) 
   t = Timer("foo.runAlgorithm()", 'from __main__ import foo')
   print t.timeit(2)

作者: xuwangyin   发布时间: 2011-05-13