[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
>>> x = fastset.Set([(1, 2), (3, 4)])
>>> x & fastset.Set([(3, 4), (1, 5)])
<Set:[(3, 4)]>

Timing the results under Python 3.1


So how did we do on the optimization front this time? Again, guesses aren’t usually
good enough, though algorithmic complexity seems a compelling piece of evidence
here. To be sure, Example 18-12 codes a script to compare set class performance. It
reuses the timer module of Example 18-6 used earlier to compare stacks (our code may
implement different objects, but it doesn’t warp time).


Example 18-12. PP4E\Dstruct\Basic\settime.py


"compare set alternatives performance"
import timer, sys
import set, fastset


def setops(Class): # 3.X: range okay
a = Class(range(50)) # a 50-integer set
b = Class(range(20)) # a 20-integer set
c = Class(range(10))
d = Class(range(5))
for i in range(5):
t = a & b & c & d # 3 intersections
t = a | b | c | d # 3 unions


if name == 'main':
rept = int(sys.argv[1])
print('set => ', timer.test(rept, setops, set.Set))
print('fastset =>', timer.test(rept, setops, fastset.Set))


The setops function makes four sets and combines them with intersection and union
operators five times. A command-line argument controls the number of times this
whole process is repeated. More accurately, each call to setops makes 34 Set instances
(4 + [5 × (3 + 3)]) and runs the intersect and union methods 15 times each (5 × 3) in
the for loop’s body. The performance improvement is equally dramatic this time
around, on the same Windows 7 laptop under Python 3.1:


C:\...\PP4E\Dstruct\Basic> python settime.py 50
set => 0.637593916437
fastset => 0.20435049302

C:\...\PP4E\Dstruct\Basic> python settime.py 100
set => 1.21924758303
fastset => 0.393896570828

C:\...\PP4E\Dstruct\Basic> python settime.py 200
set => 2.51036677716
fastset => 0.802708664223

Implementing Sets | 1381
Free download pdf