Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

timeit.timeit variable importing in python

I am trying to use timeit.timeit() in order to find how much time it takes to execute a specific line of code. The problem is that this line includes variables and I need to import them somehow, so my question is how? In order to be more clear, the code looks something like this:

def func():
    var1 = 'aaa'
    var2 = 'aab'
    t1 = timeit.timeit('var1==var2', 'from __main__ import ___', number = 10**4) #  here I'm missing what to put after the import

If I were trying to execute this code in __main__ I would just import the variable directly with 'from __main__ import var1, var2' Any solution for this kind of issue?

like image 383
pystudent Avatar asked Jul 21 '15 22:07

pystudent


People also ask

What is import Timeit in Python?

Source code: Lib/timeit.py. This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times.

How do you use %% Timeit in Jupyter?

The “%timeit” is a line magic command in which the code consists of a single line or should be written in the same line for measuring the execution time. In the “%timeit” command, the particular code is specified after the “%timeit” is separated by a space.

What does %% time mean in Python?

%%time is a magic command. It's a part of IPython. %%time prints the wall time for the entire cell whereas %time gives you the time for first line only. Using %%time or %time prints 2 values: CPU Times.


2 Answers

timeit.Timer takes a callable as well as a string to eval

Changed in version 2.6: The stmt and setup parameters can now also take objects that are callable without arguments. This will embed calls to them in a timer function that will then be executed by timeit(). Note that the timing overhead is a little larger in this case because of the extra function calls.

(also see the source, look for elif hasattr(stmt, '__call__'):).

Create a closure over the variables and pass it to timeit:

def func():
    var1 = 'aaa'
    var2 = 'aab'
    t1 = timeit.timeit(lambda: var1 == var2, number = 10**4)

or equivalently:

def func():
    var1 = 'aaa'
    var2 = 'aab'
    def closure():
        return var1 == var2
    t1 = timeit.timeit(closure, number = 10**4)
like image 177
Russia Must Remove Putin Avatar answered Oct 15 '22 08:10

Russia Must Remove Putin


The accepted answer didn't work for me inside pdb debugger and a class method. The solution that worked is to add the variables to globals():

globals()['var1'] = var1
globals()['var2'] = var2
timeit.timeit(lambda: var1 == var2, number = 10**4)
like image 25
Dennis Golomazov Avatar answered Oct 15 '22 06:10

Dennis Golomazov