Debian Codegraph @

benchmark/benchbase.py

raw
1 import sys, re, string, copy, gc
2 import itertools
3 import time
4 from contextlib import contextmanager
5 from functools import partial
6
7
8 TREE_FACTOR = 1 # increase tree size with '-l / '-L' cmd option
9 DEFAULT_REPEAT = 9
10
11 _TEXT = "some ASCII text" * TREE_FACTOR
12 _UTEXT = u"some klingon: \uF8D2" * TREE_FACTOR
13 _ATTRIBUTES = {
14 '{attr}test1' : _TEXT,
15 '{attr}test2' : _TEXT,
16 'bla1' : _TEXT,
17 'bla2' : _TEXT,
18 'bla3' : _TEXT
19 }
20
21
22 def initArgs(argv):
23 global TREE_FACTOR
24 try:
25 argv.remove('-l')
26 # use large trees
27 TREE_FACTOR *= 2
28 except ValueError:
29 pass
30
31 try:
32 argv.remove('-L')
33 # use LARGE trees
34 TREE_FACTOR *= 2
35 except ValueError:
36 pass
37
38 ############################################################
39 # benchmark decorators
40 ############################################################
41
42 def with_attributes(*use_attributes):
43 "Decorator for benchmarks that use attributes"
44 vmap = {False : 0, True : 1}
45 values = [ vmap[bool(v)] for v in use_attributes ]
46 def set_value(function):
47 try:
48 function.ATTRIBUTES.update(values)
49 except AttributeError:
50 function.ATTRIBUTES = set(values)
51 return function
52 return set_value
53
54 def with_text(no_text=False, text=False, utext=False):
55 "Decorator for benchmarks that use text"
56 values = []
57 if no_text:
58 values.append(0)
59 if text:
60 values.append(1)
61 if utext:
62 values.append(2)
63 def set_value(function):
64 try:
65 function.TEXT.add(values)
66 except AttributeError:
67 function.TEXT = set(values)
68 return function
69 return set_value
70
71 def onlylib(*libs):
72 "Decorator to restrict benchmarks to specific libraries"
73 def set_libs(function):
74 if libs:
75 function.LIBS = libs
76 return function
77 return set_libs
78
79 def serialized(function):
80 "Decorator for benchmarks that require serialized XML data"
81 function.STRING = True
82 return function
83
84 def children(function):
85 "Decorator for benchmarks that require a list of root children"
86 function.CHILDREN = True
87 return function
88
89 def nochange(function):
90 "Decorator for benchmarks that do not change the XML tree"
91 function.NO_CHANGE = True
92 return function
93
94 def anytree(function):
95 "Decorator for benchmarks that do not depend on the concrete tree"
96 function.ANY_TREE = True
97 return function
98
99 def widetree(function):
100 "Decorator for benchmarks that use only tree 2"
101 function.TREES = "2"
102 return function
103
104 def widesubtree(function):
105 "Decorator for benchmarks that use only tree 1"
106 function.TREES = "1"
107 return function
108
109
110 ############################################################
111 # benchmark baseclass
112 ############################################################
113
114 class SkippedTest(Exception):
115 pass
116
117 class TreeBenchMark:
118 atoz = string.ascii_lowercase
119 repeat100 = range(100)
120 repeat500 = range(500)
121 repeat1000 = range(1000)
122
123 _LIB_NAME_MAP = {
124 'etree' : 'lxe',
125 'ElementTree' : 'ET',
126 'cElementTree' : 'cET'
127 }
128
129 SEARCH_TAG = "{cdefg}a00001"
130
131 def __init__(self, etree, etree_parser=None):
132 self.etree = etree
133 libname = etree.__name__.split('.')[-1]
134 self.lib_name = self._LIB_NAME_MAP.get(libname, libname)
135
136 if libname == 'etree':
137 deepcopy = copy.deepcopy
138 def set_property(root, fname):
139 xml = self._serialize_tree(root)
140 if etree_parser is not None:
141 setattr(self, fname, lambda : etree.XML(xml, etree_parser))
142 else:
143 setattr(self, fname, lambda : deepcopy(root))
144 setattr(self, fname + '_xml', lambda : xml)
145 setattr(self, fname + '_children', lambda : root[:])
146 else:
147 def set_property(root, fname):
148 setattr(self, fname, self.et_make_clone_factory(root))
149 xml = self._serialize_tree(root)
150 setattr(self, fname + '_xml', lambda : xml)
151 setattr(self, fname + '_children', lambda : root[:])
152
153 attribute_list = list(enumerate( [{}, _ATTRIBUTES] ))
154 text_list = list(enumerate( [None, _TEXT, _UTEXT] ))
155 build_name = self._tree_builder_name
156
157 self.setup_times = []
158 for tree in self._all_trees():
159 times = []
160 self.setup_times.append(times)
161 setup = getattr(self, '_setup_tree%d' % tree)
162 for an, attributes in attribute_list:
163 for tn, text in text_list:
164 root, t = setup(text, attributes)
165 times.append(t)
166 set_property(root, build_name(tree, tn, an))
167
168 def _tree_builder_name(self, tree, tn, an):
169 return '_root%d_T%d_A%d' % (tree, tn, an)
170
171 def tree_builder(self, tree, tn, an, serial, children):
172 name = self._tree_builder_name(tree, tn, an)
173 if serial:
174 name += '_xml'
175 elif children:
176 name += '_children'
177 return getattr(self, name)
178
179 def _serialize_tree(self, root):
180 return self.etree.tostring(root, encoding='UTF-8')
181
182 def et_make_clone_factory(self, elem):
183 def generate_elem(append, elem, level):
184 var = "e" + str(level)
185 arg = repr(elem.tag)
186 if elem.attrib:
187 arg += ", **%r" % elem.attrib
188 if level == 1:
189 append(" e1 = Element(%s)" % arg)
190 else:
191 append(" %s = SubElement(e%d, %s)" % (var, level-1, arg))
192 if elem.text:
193 append(" %s.text = %r" % (var, elem.text))
194 if elem.tail:
195 append(" %s.tail = %r" % (var, elem.tail))
196 for e in elem:
197 generate_elem(append, e, level+1)
198 # generate code for a function that creates a tree
199 output = ["def element_factory():"]
200 generate_elem(output.append, elem, 1)
201 output.append(" return e1")
202 # setup global function namespace
203 namespace = {
204 "Element" : self.etree.Element,
205 "SubElement" : self.etree.SubElement
206 }
207
208 # create function object
209 exec("\n".join(output), namespace)
210 return namespace["element_factory"]
211
212 def _all_trees(self):
213 all_trees = []
214 for name in dir(self):
215 if name.startswith('_setup_tree'):
216 all_trees.append(int(name[11:]))
217 return all_trees
218
219 def _setup_tree1(self, text, attributes):
220 "tree with 26 2nd level and 520 * TREE_FACTOR 3rd level children"
221 atoz = self.atoz
222 SubElement = self.etree.SubElement
223 current_time = time.time
224 t = current_time()
225 root = self.etree.Element('{abc}rootnode')
226 for ch1 in atoz:
227 el = SubElement(root, "{abc}"+ch1*5, attributes)
228 el.text = text
229 for ch2 in atoz:
230 tag = "{cdefg}%s00001" % ch2
231 for i in range(20 * TREE_FACTOR):
232 SubElement(el, tag).tail = text
233 t = current_time() - t
234 return root, t
235
236 def _setup_tree2(self, text, attributes):
237 "tree with 520 * TREE_FACTOR 2nd level and 26 3rd level children"
238 atoz = self.atoz
239 SubElement = self.etree.SubElement
240 current_time = time.time
241 t = current_time()
242 root = self.etree.Element('{abc}rootnode')
243 for ch1 in atoz:
244 for i in range(20 * TREE_FACTOR):
245 el = SubElement(root, "{abc}"+ch1*5, attributes)
246 el.text = text
247 for ch2 in atoz:
248 SubElement(el, "{cdefg}%s00001" % ch2).tail = text
249 t = current_time() - t
250 return root, t
251
252 def _setup_tree3(self, text, attributes):
253 "tree of depth 8 + TREE_FACTOR with 3 children per node"
254 SubElement = self.etree.SubElement
255 current_time = time.time
256 t = current_time()
257 root = self.etree.Element('{abc}rootnode')
258 children = [root]
259 for i in range(6 + TREE_FACTOR):
260 children = [ SubElement(c, "{cdefg}a%05d" % (i%8), attributes)
261 for i,c in enumerate(itertools.chain(children, children, children)) ]
262 for child in children:
263 child.text = text
264 child.tail = text
265 t = current_time() - t
266 return root, t
267
268 def _setup_tree4(self, text, attributes):
269 "small tree with 26 2nd level and 2 3rd level children"
270 SubElement = self.etree.SubElement
271 current_time = time.time
272 t = current_time()
273 root = self.etree.Element('{abc}rootnode')
274 for ch1 in self.atoz:
275 el = SubElement(root, "{abc}"+ch1*5, attributes)
276 el.text = text
277 SubElement(el, "{cdefg}a00001", attributes).tail = text
278 SubElement(el, "{cdefg}z00000", attributes).tail = text
279 t = current_time() - t
280 return root, t
281
282 def benchmarks(self):
283 """Returns a list of all benchmarks.
284
285 A benchmark is a tuple containing a method name and a list of tree
286 numbers. Trees are prepared by the setup function.
287 """
288 all_trees = self._all_trees()
289 benchmarks = []
290 for name in dir(self):
291 if not name.startswith('bench_'):
292 continue
293
294 method = getattr(self, name)
295
296 serialized = getattr(method, 'STRING', False)
297 children = getattr(method, 'CHILDREN', False)
298 no_change = getattr(method, 'NO_CHANGE', False)
299 any_tree = getattr(method, 'ANY_TREE', False)
300 tree_sets = getattr(method, 'TREES', None)
301
302 if hasattr(method, 'LIBS') and self.lib_name not in method.LIBS:
303 method_call = None
304 else:
305 method_call = method
306
307 if tree_sets:
308 tree_sets = tree_sets.split()
309 elif method.__doc__:
310 tree_sets = method.__doc__.split()
311 else:
312 tree_sets = ()
313
314 if tree_sets:
315 tree_tuples = [list(map(int, tree_set.split(',')))
316 for tree_set in tree_sets]
317 else:
318 try:
319 arg_count = method.func_code.co_argcount - 1
320 except AttributeError:
321 try:
322 arg_count = method.__code__.co_argcount - 1
323 except AttributeError:
324 arg_count = 1
325
326 if any_tree:
327 tree_tuples = [all_trees[-arg_count:]]
328 else:
329 tree_tuples = self._permutations(all_trees, arg_count)
330
331 for tree_tuple in tree_tuples:
332 for tn in sorted(getattr(method, 'TEXT', (0,))):
333 for an in sorted(getattr(method, 'ATTRIBUTES', (0,))):
334 benchmarks.append((name, method_call, tree_tuple,
335 tn, an, serialized, children,
336 no_change))
337
338 return benchmarks
339
340 def _permutations(self, seq, count):
341 def _permutations(prefix, remainder, count):
342 if count == 0:
343 return [ prefix[:] ]
344 count -= 1
345 perms = []
346 prefix.append(None)
347 for pos, el in enumerate(remainder):
348 new_remainder = remainder[:pos] + remainder[pos+1:]
349 prefix[-1] = el
350 perms.extend( _permutations(prefix, new_remainder, count) )
351 prefix.pop()
352 return perms
353 return _permutations([], seq, count)
354
355 ############################################################
356 # Prepare and run benchmark suites
357 ############################################################
358
359 def buildSuites(benchmark_class, etrees, selected):
360 benchmark_suites = list(map(benchmark_class, etrees))
361
362 # sorted by name and tree tuple
363 benchmarks = [ sorted(b.benchmarks()) for b in benchmark_suites ]
364
365 selected = [ re.compile(r).search for r in selected ]
366
367 if selected:
368 benchmarks = [ [ b for b in bs
369 if [ match for match in selected
370 if match(b[0]) ] ]
371 for bs in benchmarks ]
372
373 return benchmark_suites, benchmarks
374
375 def build_treeset_name(trees, tn, an, serialized, children):
376 text = {0:'-', 1:'S', 2:'U'}[tn]
377 attr = {0:'-', 1:'A'}[an]
378 ser = {True:'X', False:'T'}[serialized]
379 chd = {True:'C', False:'R'}[children]
380 return "%s%s%s%s T%s" % (text, attr, ser, chd, ',T'.join(map(str, trees))[:6])
381
382 def printSetupTimes(benchmark_suites):
383 print("Setup times for trees in seconds:")
384 for b in benchmark_suites:
385 sys.stdout.write("%-3s: " % b.lib_name)
386 for an in (0,1):
387 for tn in (0,1,2):
388 sys.stdout.write(' %s ' %
389 build_treeset_name((), tn, an, False, False)[:2])
390 print('')
391 for i, tree_times in enumerate(b.setup_times):
392 print(" T%d: %s" % (i+1, ' '.join("%6.4f" % t for t in tree_times)))
393 print('')
394
395
396 def autorange(bench_func, min_runtime=0.2, max_number=None, timer=time.perf_counter):
397 i = 1
398 while True:
399 for j in 1, 2, 5:
400 number = i * j
401 if max_number is not None and number >= max_number:
402 return max_number
403 time_taken = bench_func(number)
404 if time_taken >= min_runtime:
405 return number
406 i *= 10
407
408
409 @contextmanager
410 def nogc():
411 gc.collect()
412 gc.disable()
413 try:
414 yield
415 finally:
416 gc.enable()
417
418
419 def runBench(suite, method_name, method_call, tree_set, tn, an,
420 serial, children, no_change, timer=time.perf_counter, repeat=DEFAULT_REPEAT):
421 if method_call is None:
422 raise SkippedTest
423
424 rebuild_trees = not no_change and not serial
425 tree_builders = [ suite.tree_builder(tree, tn, an, serial, children)
426 for tree in tree_set ]
427
428 def new_trees(count=range(len(tree_builders)), trees=[None] * len(tree_builders)):
429 for i in count:
430 trees[i] = tree_builders[i]()
431 return tuple(trees)
432
433 if rebuild_trees:
434 def time_benchmark(loops):
435 t_all_calls = 0.0
436 for _ in range(loops):
437 run_benchmark = partial(method_call, *new_trees())
438 t_one_call = timer()
439 run_benchmark()
440 t_one_call = timer() - t_one_call
441 t_all_calls += t_one_call
442 return t_all_calls
443 else:
444 def time_benchmark(loops, run_benchmark=partial(method_call, *new_trees())):
445 _loops = range(loops)
446 t_one_call = timer()
447 for _ in _loops:
448 run_benchmark()
449 t_all_calls = timer() - t_one_call
450 return t_all_calls
451
452 time_benchmark(1) # run once for tree warm-up
453
454 with nogc():
455 # Adjust "min_runtime" to avoid long tree rebuild times for short benchmarks.
456 inner_loops = autorange(
457 time_benchmark,
458 min_runtime=0.1 if rebuild_trees else 0.2,
459 max_number=200 if rebuild_trees else None,
460 )
461
462 times = []
463 for _ in range(repeat):
464 with nogc():
465 t_one_call = time_benchmark(inner_loops) / inner_loops
466 times.append(1000.0 * t_one_call) # msec
467 gc.collect()
468 return times
469
470
471 def runBenchmarks(benchmark_suites, benchmarks, repeat=DEFAULT_REPEAT):
472 for bench_calls in zip(*benchmarks):
473 for lib, (bench, benchmark_setup) in enumerate(zip(benchmark_suites, bench_calls)):
474 bench_name = benchmark_setup[0]
475 tree_set_name = build_treeset_name(*benchmark_setup[-6:-1])
476 sys.stdout.write("%-3s: %-28s (%-10s) " % (
477 bench.lib_name, bench_name[6:34], tree_set_name))
478 sys.stdout.flush()
479
480 try:
481 result = runBench(bench, *benchmark_setup, repeat=repeat)
482 except SkippedTest:
483 print("skipped")
484 except KeyboardInterrupt:
485 print("interrupted by user")
486 sys.exit(1)
487 except Exception:
488 exc_type, exc_value = sys.exc_info()[:2]
489 print("failed: %s: %s" % (exc_type.__name__, exc_value))
490 exc_type = exc_value = None
491 else:
492 result.sort()
493 t_min, t_median, t_max = result[0], result[len(result) // 2], result[-1]
494 print(f"{t_min:9.4f} msec/pass, best of ({t_min:9.4f}, {t_median:9.4f}, {t_max:9.4f})")
495
496 if len(benchmark_suites) > 1:
497 print('') # empty line between different benchmarks
498
499
500 ############################################################
501 # Main program
502 ############################################################
503
504 def main(benchmark_class):
505 import_lxml = True
506 callgrind_zero = False
507 if len(sys.argv) > 1:
508 try:
509 sys.argv.remove('-i')
510 # run benchmark 'inplace'
511 sys.path.insert(0, 'src')
512 except ValueError:
513 pass
514
515 try:
516 sys.argv.remove('-nolxml')
517 # run without lxml
518 import_lxml = False
519 except ValueError:
520 pass
521
522 try:
523 sys.argv.remove('-z')
524 # reset callgrind after tree setup
525 callgrind_zero = True
526 except ValueError:
527 pass
528
529 initArgs(sys.argv)
530
531 _etrees = []
532 if import_lxml:
533 from lxml import etree
534 _etrees.append(etree)
535 print("Using lxml %s (with libxml2 %s)" % (
536 etree.__version__, '.'.join(map(str, etree.LIBXML_VERSION))))
537
538 try:
539 sys.argv.remove('-fel')
540 except ValueError:
541 pass
542 else:
543 # use fast element creation in lxml.etree
544 etree.set_element_class_lookup(
545 etree.ElementDefaultClassLookup())
546
547 if len(sys.argv) > 1:
548 try:
549 # 'all' ?
550 sys.argv.remove('-a')
551 except ValueError:
552 pass
553 else:
554 try:
555 from xml.etree import ElementTree as ET
556 _etrees.append(ET)
557 except ImportError:
558 pass
559
560 if not _etrees:
561 print("No library to test. Exiting.")
562 sys.exit(1)
563
564 print("Running benchmarks in Python %s" % (sys.version_info,))
565
566 print("Preparing test suites and trees ...")
567 selected = set( sys.argv[1:] )
568 benchmark_suites, benchmarks = buildSuites(benchmark_class, _etrees, selected)
569
570 print("Running benchmark on", ', '.join(b.lib_name
571 for b in benchmark_suites))
572 print('')
573
574 printSetupTimes(benchmark_suites)
575
576 if callgrind_zero:
577 with open("callgrind.cmd", 'w') as cmd:
578 cmd.write('+Instrumentation\n')
579 cmd.write('Zero\n')
580
581 runBenchmarks(benchmark_suites, benchmarks, repeat=DEFAULT_REPEAT)