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)
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
Tom Cruise
  • 509
  • 1
  • 6
  • 10
  • 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. – BrenBarn Jun 04 '13 at 18:13

3 Answers3

8

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"))
zmo
  • 24,463
  • 4
  • 54
  • 90
2

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!

John Haberstroh
  • 465
  • 4
  • 11
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()
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94