[英]How to pass parameters to timeit function in python?
import timeit
#those are the parameters that need to be passed
list1=["Ahmed","Ahmedd"]
#loop through the parameters
for x in list1:
mysetup=x
#the function to be tested
mycode='''
#testing if the string is unique
def is_unique_chars_using_set(string):
#Solution Using Set
characters_seen = set()
for char in string:
if char in characters_seen:
return False
characters_seen.add(char)
return True'''
print (timeit.timeit(stmt = mycode,number = 1000000))
如何將這些參數傳遞給timeit
?
這里的代碼實際上並沒有使用列表。 timeit 無法查看循環內部。 (即它應該在適當的范圍內)
下面的代碼將為您工作
import timeit
#those are the parameters that need to be passed
list1=["Ahmed","Ahmedd"]
#loop through the parameters
#the function to be tested
mycode='''
#testing if the string is unique
def is_unique_chars_using_set(string):
#Solution Using Set
characters_seen = set()
for char in string:
if char in characters_seen:
return False
characters_seen.add(char)
return True'''
print (timeit.timeit(stmt = mycode,number = 1000000))
如果需要 for 循環,那么您需要在“我的代碼”中包含 for 循環
import timeit
mycode='''
list1=["Ahmed","Ahmedd"]
for x in list1:
mysetup=x
#testing if the string is unique
def is_unique_chars_using_set(string):
#Solution Using Set
characters_seen = set()
for char in string:
if char in characters_seen:
return False
characters_seen.add(char)
return True'''
print (timeit.timeit(stmt = mycode,number = 1000000))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.