Using timeit module in a function with arguments
Asked Answered
C

3

5

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)
Cowslip answered 4/6, 2013 at 18:11 Comment(1)
The same way? print(timeit.timeit("test(5)", setup="from __main__ import test")). If you want to use an argument that's an object you define outside the timeit code, you have to import it like anything else. The timeit string is just normal Python code, everything works as usual.Twinkle
B
9

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"))
Brahma answered 4/6, 2013 at 18:14 Comment(1)
(I love it when the answer is in the question :-p)Brahma
E
3

Here's one solution that worked for me in this exact situation, as long as your arguments are not tremendous matrices or anything like that.


Let's say that I want to test a function foo(a,b,c) with values that I've initialized inside of my main function. I can make the call to the following without changing my code,

timeit.Timer('foo({},{},{})'.format(a,b,c), "from __main__ import foo")

If your arguments are strings, then you must re-introduce the quotes around the values:

timeit.Timer('foo("{}","{}","{}")'.format(a,b,c), "from __main__ import foo")

As a final warning, you must consider that your arguments will pass through the str() format, which may cause them to lose precision and integrity of various kinds. Please check your inputs if you use this method!

Emanuel answered 14/5, 2014 at 0:16 Comment(0)
S
0

You want to use:

def main():
    import timeit
    print(timeit.timeit("test(some_object)")) # don't need to use the 'setup'

def test(my_object):
    lst = []
    for i in range(100):
        lst.append(my_object)

if __name__ == '__main__':
    main()
Simla answered 4/6, 2013 at 18:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.