简体   繁体   English

如何将列表作为参数函数传递给 Python 3.2.3 中的 timeit 调用?

[英]How to pass a list as parameter function into a timeit call in Python 3.2.3?

function_to_test(test, mylist): #test as an int, mylist as a list of int
     do_something    
     return something

function_generates_a_list(min, max): #min, max are int
     do_something
     return a_List

I need to timeit the function_to_test and only this one.我需要给 function_to_test 计时,而且只有这个。 The purpose is to test code in order to determine which one is the best to test if a int is in a list of int.目的是测试代码以确定哪个最适合测试 int 是否在 int 列表中。 ( test is a googolplex and mylist is a huge list starting from min to max). test是一个 googolplex 而mylist是一个从最小到最大的巨大列表)。 Yes, I already know the result of the function, I need to know how many times it will cost.是的,我已经知道函数的结果,我需要知道它会花费多少次。

My problem is: which syntax have I to use with timeit if I want to pass a global list as a local parameter of a function I test?我的问题是:如果我想将全局列表作为我测试的函数的局部参数传递,我应该与 timeit 一起使用哪种语法?

The easiest way to do this is to create a function that takes no arguments, and calls your function with whatever arguments it needs:最简单的方法是创建一个不带参数的函数,并使用它需要的任何参数调用您的函数:

mylist = function_generates_a_list()
def newfunc():
   function_to_test(mylist)

You can then call timeit(newfunc) .然后您可以调用timeit(newfunc) You could also do this with a lambda expression - timeit(lambda: function_to_test(mylist)) is exactly equivalent to the above.您也可以使用 lambda 表达式执行此操作 - timeit(lambda: function_to_test(mylist))与上述完全等效。 If you're using timeit module-wise (ie, doing python -m timeit ... ), you could also do this:如果您正在使用timeit模块(即,执行python -m timeit ... ),您也可以这样做:

python -m timeit --setup='import mymodule' 'mymodule.newfunc()'

You could avoid having newfunc altogether by having a sufficiently convoluted setup string (the call to function_generates_a_list has to be in setup, possibly (as here) but not necessarily by happening when you import the module, if you don't want it to be part of your timings), but having the function makes things more flexible and less annoying.您可以通过使用足够复杂的setup字符串newfunc完全避免使用newfunc (对function_generates_a_list的调用必须在设置中,可能(如此处)但不一定在导入模块时发生,如果您不希望它成为一部分您的时间),但拥有该功能可以使事情变得更加灵活且不那么烦人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM