martineau

return a value if substring not found benchmark

Nov 4th, 2017
118
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python2
  2. # https://stackoverflow.com/questions/47107125/how-to-return-a-value-if-a-specific-iterated-sub-string-not-found-in-value
  3.  
  4. from __future__ import print_function
  5. from collections import namedtuple
  6. import sys
  7. from textwrap import dedent
  8. import timeit
  9. import traceback
  10.  
  11. N = 10000  # number of executions of each "algorithm"
  12. R = 3  # number of Repetitions of executions
  13.  
  14. # common setup for all testcases (executed before any algorithm specific setup)
  15. COMMON_SETUP = dedent("""
  16.    stringsList = ["Icantbeapart_of_yourlist_asI_am_in_Junk", "youAre", "MeeToooo", "#junk"]
  17.    excluded = 'I', 'am', '#junk'
  18. """)
  19.  
  20. class TestCase(namedtuple('CodeFragments', ['setup', 'test'])):
  21.     def __new__(cls, setup, test):
  22.         """ Dedent code fragment in each string argument. """
  23.         return tuple.__new__(cls, (dedent(setup), dedent(test)))
  24.  
  25. testcases = {
  26.     "martineau": TestCase("""
  27.        def filterJunk(x, excluded):
  28.            def not_excluded(s):
  29.                for ex in excluded:
  30.                    if ex in s:
  31.                        return False
  32.                return True
  33.  
  34.            return filter(not_excluded, x)
  35.        """, """
  36.        res = filterJunk(stringsList, excluded)
  37.        """
  38.     ),
  39.     "AGN Gazer 1": TestCase("""
  40.        """, """
  41.        res = [x for x in stringsList if not [e for e in excluded if e in x]]
  42.        """
  43.     ),
  44.     "AGN Gazer 2": TestCase("""
  45.        from itertools import dropwhile
  46.        """, """
  47.        res = [x for x in stringsList if not list(dropwhile(lambda t: t not in x, excluded))]
  48.        """
  49.     ),
  50. }
  51.  
  52. # collect timing results of executing each testcase multiple times
  53. try:
  54.     results = [
  55.         (label,
  56.          min(timeit.repeat(testcases[label].test,
  57.                            setup=COMMON_SETUP + testcases[label].setup,
  58.                            repeat=R, number=N)),
  59.         ) for label in testcases
  60.     ]
  61. except Exception:
  62.     traceback.print_exc(file=sys.stdout)  # direct output to stdout
  63.     sys.exit(1)
  64.  
  65. # display results
  66. major, minor, micro = sys.version_info[:3]
  67. print('Fastest to slowest execution speeds using Python {}.{}.{}\n'
  68.       '({:,d} executions, best of {:d} repetitions)'.format(major, minor, micro, N, R))
  69. print('')
  70.  
  71. longest = max(len(result[0]) for result in results)  # length of longest label
  72. ranked = sorted(results, key=lambda t: t[1]) # ascending sort by execution time
  73. fastest = ranked[0][1]
  74. for result in ranked:
  75.     print('{:>{width}} : {:9.6f} secs, rel speed {:5.2f}x, {:6.2f}% slower '
  76.           ''.format(
  77.                 result[0], result[1], round(result[1]/fastest, 2),
  78.                 round((result[1]/fastest - 1) * 100, 2),
  79.                 width=longest))
  80. print('')
RAW Paste Data