Hi, I'm having a syntax issue with timeit while trying to measure the time taken by a function meant to concatenate two linked lists.

def get_time() :
       import cell
       import timeit
       for i in range( 1, 16 ):
                lista = cell.make_list(i) #this function return the root of a sll filled with sequential integers 1 through i * 1000
                listb = cell.make_list(i)
                mytime = timeit.Timer( 'list_concat_copy( lista, listb )', 'from cell import list_concat_copy' )
                alpha = mytime.timeit( 1 )
                print "1 run of list_concat_copy with list size " + str( i * 1000 ) + " took " + str( alpha ) + " seconds."

This is the error I receive:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "problem3.py", line 12, in main
alpha = mytime.timeit( 1 )
File "/usr/lib/python2.6/timeit.py", line 193, in timeit
timing = self.inner(it, self.timer)
File "<timeit-src>", line 6, in inner
NameError: global name 'lista' is not defined

I can see that timeit.Timer needs to import the arguments for list_concat_copy, but I'm not sure how to do that. It won't allow a second from statement, at least not the way I tried it, and I've tried moving statements in and out of different scopes to try and get a solution, but it had no positive effect. Any suggestions would be most welcome!

The Timer executes the code in a new namespace. This namespace doesn't know lista and listb because they are not in the name space. If you create a module that declares and sets these variables, you could then import it using the Timer's setup statement. (If you need the cell module, just import it in your module and it will be available.)

It says in the timeit module that it is really only suitable for measuring the performance of small snippets of code. If you want to be more serious about profiling code, consider learning about the "profile" module.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.