Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using timeit module in a function with arguments

Tags:

python

timeit

Example from documentation

def test():
    """Stupid test function"""
    L = []
    for i in range(100):
        L.append(i)

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test()", setup="from __main__ import test"))

but how to call a function with parameters, for example, a function like this:

def test(some_object):
    """Stupid test function"""
    L = []
    for i in range(100):
        L.append(some_object)
like image 869
Tom Cruise Avatar asked Jun 04 '13 18:06

Tom Cruise


People also ask

Can you use Timeit on a function in Python?

timeit() function returns the number of seconds it took to execute the code.

What is the Timeit module used for?

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.


1 Answers

err, if I get your question right, you're just looking for that?

anobj = 42 # where it can be whatever object
def test(foo):
    pass # do something with foo

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test(anobj)", setup="from __main__ import test, anobj"))
like image 73
zmo Avatar answered Sep 25 '22 19:09

zmo