-1

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

olala
  • 4,146
  • 9
  • 34
  • 44
  • 2
    *"Doesn't produce anything"* - really?! I'd expect `NameError: name 'i' is not defined`, which gives you a pretty good clue to the issue. – jonrsharpe Jun 24 '15 at 16:11
  • 1
    In the future, please give more detail than "doesn't produce anything". – user2357112 Jun 24 '15 at 16:12
  • OK. guys, I used PyCharm python console and it didn't produce anything there.. I just tried running it on terminal and saw the error.. – olala Jun 24 '15 at 16:13

1 Answers1

1

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • @Martjin Pieters I run the test and it seems to me that the algorithm is quadratic, please see the edits. is it correct? – olala Jun 25 '15 at 14:13
  • @olala: yes, it is quadratic, because for ever N times you run the outer loop, you run the inner loop another N times. – Martijn Pieters Jun 25 '15 at 14:15