Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python2
- # https://stackoverflow.com/questions/47107125/how-to-return-a-value-if-a-specific-iterated-sub-string-not-found-in-value
- from __future__ import print_function
- from collections import namedtuple
- import sys
- from textwrap import dedent
- import timeit
- import traceback
- N = 10000 # number of executions of each "algorithm"
- R = 3 # number of Repetitions of executions
- # common setup for all testcases (executed before any algorithm specific setup)
- COMMON_SETUP = dedent("""
- stringsList = ["Icantbeapart_of_yourlist_asI_am_in_Junk", "youAre", "MeeToooo", "#junk"]
- excluded = 'I', 'am', '#junk'
- """)
- class TestCase(namedtuple('CodeFragments', ['setup', 'test'])):
- def __new__(cls, setup, test):
- """ Dedent code fragment in each string argument. """
- return tuple.__new__(cls, (dedent(setup), dedent(test)))
- testcases = {
- "martineau": TestCase("""
- def filterJunk(x, excluded):
- def not_excluded(s):
- for ex in excluded:
- if ex in s:
- return False
- return True
- return filter(not_excluded, x)
- """, """
- res = filterJunk(stringsList, excluded)
- """
- ),
- "AGN Gazer 1": TestCase("""
- """, """
- res = [x for x in stringsList if not [e for e in excluded if e in x]]
- """
- ),
- "AGN Gazer 2": TestCase("""
- from itertools import dropwhile
- """, """
- res = [x for x in stringsList if not list(dropwhile(lambda t: t not in x, excluded))]
- """
- ),
- }
- # collect timing results of executing each testcase multiple times
- try:
- results = [
- (label,
- min(timeit.repeat(testcases[label].test,
- setup=COMMON_SETUP + testcases[label].setup,
- repeat=R, number=N)),
- ) for label in testcases
- ]
- except Exception:
- traceback.print_exc(file=sys.stdout) # direct output to stdout
- sys.exit(1)
- # display results
- major, minor, micro = sys.version_info[:3]
- print('Fastest to slowest execution speeds using Python {}.{}.{}\n'
- '({:,d} executions, best of {:d} repetitions)'.format(major, minor, micro, N, R))
- print('')
- longest = max(len(result[0]) for result in results) # length of longest label
- ranked = sorted(results, key=lambda t: t[1]) # ascending sort by execution time
- fastest = ranked[0][1]
- for result in ranked:
- print('{:>{width}} : {:9.6f} secs, rel speed {:5.2f}x, {:6.2f}% slower '
- ''.format(
- result[0], result[1], round(result[1]/fastest, 2),
- round((result[1]/fastest - 1) * 100, 2),
- width=longest))
- print('')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement