Ticket #12826: benchmark.py

File benchmark.py, 1.5 KB (added by Sebastian Noack, 15 years ago)
Line 
1import time
2import sys
3import gc
4
5gc.disable()
6sys.setcheckinterval(sys.maxint)
7
8class WithSlots(object):
9 __slots__ = ('a', 'b', 'c')
10
11class WithSlotsAndCtor(object):
12 __slots__ = ('a', 'b', 'c')
13
14 def __init__(self):
15 self.a = 1
16 self.b = 2
17 self.c = 3
18
19class WithoutSlots(object):
20 pass
21
22class WithoutSlotsAndCtor(object):
23 def __init__(self):
24 self.a = 1
25 self.b = 2
26 self.c = 3
27
28def benchmark(cls):
29 t = time.time
30 l = []
31
32 for i in xrange(5):
33 s = t()
34
35 for i in xrange(100000):
36 cls()
37
38 l.append(t() - s)
39
40 return l
41
42def print_benchmarks(*classes):
43 columns = [
44 {'title': '', 'func': lambda cls, dur: cls.__name__},
45 {'title': 'Avg.', 'func': lambda cls, dur: '%.3f' % (sum(dur) / len(dur))},
46 {'title': 'Min.', 'func': lambda cls, dur: '%.3f' % min(dur)},
47 {'title': 'Max.', 'func': lambda cls, dur: '%.3f' % max(dur)},
48 ]
49
50 rows = []
51 for cls in classes:
52 durations = benchmark(cls)
53 rows.append([col['func'](cls, durations) for col in columns])
54
55 widthes = [max(len(row[i]) for row in rows) for i in xrange(len(columns))]
56
57 print ' | '.join(col['title'].ljust(widthes[i]) for i, col in enumerate(columns))
58 for row in rows:
59 print '-+-'.join('-' * w for w in widthes)
60 print ' | '.join(row[i].ljust(widthes[i]) for i in xrange(len(columns)))
61
62# c1_lenth = max(len(cls.__name__ for cls in classes))
63
64# print ' | '.join(' ' * c1_length
65
66print_benchmarks(WithSlots, WithSlotsAndCtor, WithoutSlots, WithoutSlotsAndCtor)
67
68#print 'Avg: %.4f' % (sum(durations) / len(durations))
69#print 'Min: %.4f' % min(durations)
70#print 'Max: %.4f' % max(durations)
Back to Top