简体   繁体   中英

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))

How to pass those parameters to timeit ?

The code here doesn't uses the list actually. The timeit cannot look inside the loop. (ie. It should be in proper range)

The code below will work for you

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))

If the for loop is needed, Then you need to include the for loop inside the "my code"

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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