2
I need to check the running time of a function using the module timeit
of Python 3, but it does not accept that I pass the value inside the function by a variable.
If I replace the line:
tempo = timeit.timeit("comp_string(string, 'Fred')", "from __main__ import
for
tempo = timeit.timeit("comp_string('Fred', 'Fred')", "from __main__ import
works, but passing the value Fred
in the variable does not work.
How can I fix this?
Follows the code:
'''
Comparação de Strings por Força Bruta
'''
import timeit
def comp_string(string_new, string_origin):
for i, c in enumerate(string_origin):
if string_new[i] != c:
return False
return True
def calcula_exec(string):
#Calcula tempo de execução do código
tempo = timeit.timeit("comp_string(string, 'Fred')", "from __main__ import comp_string")
return tempo
Perfect utluiz! I just didn’t understand why {0}. What if the parameter was a list? Just put format(list)?
– fredsilva
{0}
would be the first argument offormat()
. In the example I gave, the method only works with string (str
). But it could also work with a list as long as you represent that list in a string, for example, using the methodjoin
. If you havelist = [1, 2, 3]
, do', '.join(str(i) for i in list)
.– utluiz