python: syntax issue with timeit and passing arguments

177 views Asked by At

I want to test the Big-O performance of the test1(n) function below so I'm trying to use timeit to see the performance. However, the code right now doesn't produce anything...

I think the issue is in the t1 = timeit.Timer line with the argument not passing into the test1(n) function. I don't know how to fix it. Any help? Thanks!

def test1(n):
    for i in range(n):
        for j in range(n):
            k = 2 + 2


if __name__ == '__main__':
    import timeit

    for i in range(1000000, 100000001, 1000000):
        t1 = timeit.Timer("test1(i)", setup="from __main__ import test1")
        x = list(range(i))
        tm = t1.timeit(number=1000)
        print x
        print("%15.5f" % tm)

Edit:

So the result is it's quadratic O(n^2)?enter image description here

1

There are 1 answers

2
Martijn Pieters On BEST ANSWER

You need to import i as well:

t1 = timeit.Timer("test1(i)", setup="from __main__ import test1, i")

Every name used in the statements being tested must be imported explicitly. The name x (bound to the range for i) is not touched upon by the timed code and printing it won't make any difference here.