Check runtime with timeit

Asked

Viewed 1,197 times

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

1 answer

1


You can use include the literal value of the parameter string in the function of the defendant timeit using the method format(), thus:

"comp_string('{0}', 'Fred')".format(string)

The full function would be:

def calcula_exec(string):       
    #Calcula tempo de execução do código
    tempo = timeit.timeit("comp_string('{0}', 'Fred')".format(string), "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)?

  • {0} would be the first argument of format(). 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 method join. If you have list = [1, 2, 3], do ', '.join(str(i) for i in list).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.