将变量传递给函数时如何使用python timeit?

Los*_*oul 73 python debugging benchmarking

我正在努力使用timeit并且想知道是否有人有任何提示

基本上我有一个函数(我传递一个值),我想测试速度并创建它:

if __name__=='__main__':
    from timeit import Timer
    t = Timer(superMegaIntenseFunction(10))
    print t.timeit(number=1)
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,我得到了来自timeit模块的奇怪错误:

ValueError: stmt is neither a string nor callable
Run Code Online (Sandbox Code Playgroud)

如果我自己运行该功能,它可以正常工作.当我在模块中包装它时,我得到了错误(我尝试使用双引号而没有..sameoutput).

任何建议都会很棒!

谢谢!

Pab*_*blo 119

使它成为可调用的:

if __name__=='__main__':
    from timeit import Timer
    t = Timer(lambda: superMegaIntenseFunction(10))
    print(t.timeit(number=1))
Run Code Online (Sandbox Code Playgroud)

应该管用

  • 哦,但lambda增加了一些开销,所以不适合测试小东西.`timeit 5*5`是33 ns而`timeit(lambda:5*5)()`是233 ns. (15认同)
  • 如果只是在某处的文档中 (6认同)

Kar*_*tel 23

Timer(superMegaIntenseFunction(10))表示"调用superMegaIntenseFunction(10),然后将结果传递给Timer".这显然不是你想要的.Timer期望一个可调用的(就像听起来:可以调用的东西,比如一个函数),或者一个字符串(这样它就可以将字符串的内容解释为Python代码).Timer通过反复调用可调用事物并查看花费了多少时间来工作.

Timer(superMegaIntenseFunction)会传递类型检查,因为它superMegaIntenseFunction是可调用的.但是,Timer不知道要传递给哪些值superMegaIntenseFunction.

当然,解决这个问题的简单方法是使用带代码的字符串.我们需要将一个'setup'参数传递给代码,因为字符串在新的上下文中被"解释为代码" - 它无法访问相同globals的代码,因此您需要运行另一段代码来进行定义可用 - 请参阅@ oxtopus的回答.

使用lambda(如@ Pablo的回答),我们可以将参数绑定10到调用superMegaIntenseFunction.所有这一切,我们正在做的是创造另一个功能,即不带任何参数,并调用superMegaIntenseFunction10.这就像你曾经def创建过这样的另一个函数,除了新函数没有得到一个名字(因为它不需要一个).


Aus*_*all 18

你应该传递一个字符串.即

t = Timer('superMegaIntenseFunction(10)','from __main__ import superMegaIntenseFunction')
Run Code Online (Sandbox Code Playgroud)