test_benchmarks.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """Tests to show that the benchmarks we based our speed optimizations on are
  2. still valid"""
  3. import unittest
  4. from functools import partial
  5. from timeit import timeit
  6. timeit = partial(timeit, number=500000)
  7. class TestBenchmarks(unittest.TestCase):
  8. def test_lists_vs_dicts(self):
  9. """See what's faster at int key lookup: dicts or lists."""
  10. list_time = timeit('item = l[9000]', 'l = [0] * 10000')
  11. dict_time = timeit('item = d[9000]', 'd = {x: 0 for x in range(10000)}')
  12. # Dicts take about 1.6x as long as lists in Python 2.6 and 2.7.
  13. self.assertTrue(list_time < dict_time, '%s < %s' % (list_time, dict_time))
  14. def test_call_vs_inline(self):
  15. """How bad is the calling penalty?"""
  16. no_call = timeit('l[0] += 1', 'l = [0]')
  17. call = timeit('add(); l[0] += 1', 'l = [0]\n'
  18. 'def add():\n'
  19. ' pass')
  20. # Calling a function is pretty fast; it takes just 1.2x as long as the
  21. # global var access and addition in l[0] += 1.
  22. self.assertTrue(no_call < call, '%s (no call) < %s (call)' % (no_call, call))
  23. def test_startswith_vs_regex(self):
  24. """Can I beat the speed of regexes by special-casing literals?"""
  25. re_time = timeit(
  26. 'r.match(t, 19)',
  27. 'import re\n'
  28. "r = re.compile('hello')\n"
  29. "t = 'this is the finest hello ever'")
  30. startswith_time = timeit("t.startswith('hello', 19)",
  31. "t = 'this is the finest hello ever'")
  32. # Regexes take 2.24x as long as simple string matching.
  33. self.assertTrue(startswith_time < re_time,
  34. '%s (startswith) < %s (re)' % (startswith_time, re_time))