Thursday, May 8, 2008

Ever wondered which solution to a problem is faster? Python has a nice timeit module, which allows you to stop the time for “small code snippets”. But what if you want to test a small chunk of code? Yes, you can do that, too. But I could not figure out from the standard help text.

Desperate, I downloaded some timeit examples with sample codes tested from PyMOTW, and figured out what to do.

First, you write a simple module, i.e. a python file without main script. Write just the functions you want to test.

and then you run

python -m timeit "import <module_name>; <module_name>.<function_name>()

And you should soon get your timing results.

Here is a module speedtest, where I measured whether makeDict() ist faster than makeList().

# speedtest 1.0, Sven Siegmund
# run with "python -m timeit "import speedtest; speedtest.<function_name>()"

def makeDict(value=1023): # 100 loops, best of 3: 2.08 msec per loop
aDict = {}
for i in range(value):
key = chr(97+i%26)

def updateList(somekey, somevalue, somelist): # needed in makeList(), not to be tested alone
for listMember in somelist:
if somekey in listMember[0]:
listMember[1] = somevalue
return True
return False

def makeList(value=1023): # 100 loops, best of 3: 5.5 msec per loop
aList = []
for i in range(value):
key = chr(97+i%26)
if not updateList(key, i, aList):
aList.append([key, i])

No comments: