Check execution time with timeit

2

I need to check the runtime of a function using the timeit module of Python 3, however 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 

by

tempo = timeit.timeit("comp_string('Fred', 'Fred')", "from __main__ import 

It works, but passing the value Fred to the variable does not work.

How can I fix this? Here is 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
    
asked by anonymous 05.02.2014 / 18:42

1 answer

1

You can use include the literal value of the string parameter in the argument of the timeit function using the format() ", like this:

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

The full function would look like:

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
    
05.02.2014 / 19:30