Sonu Mishra
Sonu Mishra

Reputation: 1779

Accessing outside variables from timeit

I want to time a bunch of statements. For example:

s = """\
for i in range (0,3):
    for j in range (0,4):
        if alpha_beta[i,j] == 0 and vect2[i] != 0.0 and alpha[j] == 1 :
            print(i,j)
            alpha_beta[i,j] = vect2[i]
"""
timeit.timeit(stmt=s, number=100)

But it throws error: name 'alpha_beta' is not defined.

Variables alpha_beta, vect2 and alpha are defined earlier. I cannot include those in the timer, because that will include their initialization overheads too.

I am new to Python and an answer modifying my code will be highly appreciated.

Upvotes: 1

Views: 633

Answers (2)

vaultah
vaultah

Reputation: 46523

You could import them in setup:

timeit.timeit(stmt=s, setup='from __main__ import alpha_beta, vect2, alpha', number=100)

Starting from Python 3.5 timeit.timeit may also execute code in the provided globals namespace. Setting it to globals() will enable stmt to access names from your module's namespace:

timeit.timeit(stmt=s, number=100, globals=globals())

Upvotes: 3

Dunes
Dunes

Reputation: 40683

One solution is to provide a function rather than a string. This way your code can easily access the globals in the context it was created.

That is, your code would become:

def f():
    for i in range (0,3):
        for j in range (0,4):
            if alpha_beta[i,j] == 0 and vect2[i] != 0.0 and alpha[j] == 1 :
                print(i,j)
                alpha_beta[i,j] = vect2[i]   

timeit.timeit(stmt=f, number=100)

Upvotes: 2

Related Questions