Home > Articles > Open Source > Python

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

4.10 Example: BaseTimer

Here is another example of a template method. Figure 4–8 gives the code for a class named BaseTimer. This class will help us time the execution of algorithms. To use it, we create a subclass containing the algorithm:

class alg(BaseTimer):...
    def __init__(self,...):...
    def xeq(self): ...#do algorithm

Figure 4-8Figure 4–8 BaseTimer.

This subclass must contain a method named xeq(), which will actually execute the algorithm. The __init__() method, if any, can be used to save parameters for the trial, for example, the size of the data set to use.

To run the timing trial, create an instance of the subclass containing the algorithm, call its run() method, and then call its duration() method to get the time:

t=alg(N,....)
t.run()
print "run time for size",N,"is",t.duration()

Figure 4–9 shows a script, TimeListSet.py, to find the execution time of ListSet. There is another script to time DictSet, which is almost the same. The built-in function xrange() is like range(), but it does not construct an entire list. When used in a for statement, xrange() generates the elements that would be in the list created by range() with the same parameters. This script is executed with the command line python TimeListSet start end step, where start is the initial data set size, end is the terminating size, and step is the increment in size. Because these are converted to integers and passed to xrange(), data set size end is not included.

Figure 4-9Figure 4–9 Script to time ListSet.

Here are the first two times given by TimeListSet:

TimeSet, size= 10000 , time= 18.6961543995
TimeSet, size= 20000 , time= 85.1229013743

And here are the first two given by TimeDictSet:

TimeSet, size= 10000 , time= 0.188048481022
TimeSet, size= 20000 , time= 0.356522127812

Clearly, for large set sizes, DictSets are a lot faster.

  • + Share This
  • 🔖 Save To Your Account