4.10 Example: BaseTimer
Here is another example of a template method. Figure 48 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 48 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 49 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 49 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.