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)
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. Commented Jun 4, 2013 at 18:13

3 Answers 3

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"))
Sign up to request clarification or add additional context in comments.

1 Comment

(I love it when the answer is in the question :-p)
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!

Comments

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.