notaprogrammr
notaprogrammr

Reputation: 13

Error Output Using Timer Object in Python

I've got several functions that I need to evaluate the performance of using the timeit module.

For starters, I'm attempting to use a Timer object to evaluate a sequential search function run on a list of random integers which should return the time to execute in seconds. The function returns a value of False for -1 (since it will never find -1) but gives me the following error along with it. Here is the complete output:

False
Traceback (most recent call last):
  File "D:/.../search-test.py", line 37, in <module>
    main()
  File "D:/.../search-test.py", line 33, in main
    print(t1.timeit(number=100))
  File "C:\...\Anaconda2\lib\timeit.py", line 202, in timeit
    timing = self.inner(it, self.timer)
  File "<timeit-src>", line 6, in inner
TypeError: sequential_search() takes exactly 2 arguments (0 given)

This is my program:

from timeit import Timer
import random


def sequential_search(a_list, item):
    pos = 0
    found = False

    while pos < len(a_list) and not found:
        if a_list[pos] == item:
            found = True
        else:
            pos = pos+1

    return found


def num_gen(value):
    myrandom = random.sample(xrange(0, value), value)
    return myrandom


def main():
    new_list = num_gen(100)
    print(sequential_search(new_list, -1))
    t1 = (Timer("sequential_search()", "from __main__ import sequential_search"))
    print(t1.timeit(number=100))


if __name__ == '__main__':
main()

I'm a noob to programming and can honestly say that I'm struggling. This error doesn't make any sense to me. I don't understand why it's asking for the sequential_search function arguments when they're already passed in main(). Plugging the arguments in to the Timer statement doesn't solve the problem.

Please help me understand what I've screwed up. Thank you!

Upvotes: 1

Views: 86

Answers (1)

hashcode55
hashcode55

Reputation: 5860

This is how you make a timer object -

t1 = (Timer("sequential_search(new_list, -1)", setup="from __main__ import sequential_search, num_gen;new_list=num_gen(100);"))
print(t1.timeit(number=100))

Output -

False
0.0014021396637

It didn't work just because you were simply not passing the arguments. So just initialize the variables in setup(not necessarily though) and you are good to go.

Upvotes: 1

Related Questions