Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # https://stackoverflow.com/questions/53257607/get-closest-coordinate-in-2d-array
- from __future__ import print_function
- from collections import namedtuple
- import sys
- from random import seed, uniform
- from textwrap import dedent
- import timeit
- import traceback
- N = 1000 # Number of executions of each "algorithm".
- R = 3 # Number of repetitions of those N executions.
- NUMPTS = 10000 # Number of points.
- seed(42) # Initialize random number so the results are reproducible.
- #coordinates = [(-225.0, -299.5), (-150.0, 75.5), (0.0, 0.0), (225.0, 300.5)]
- #xy = (-222.4, -204.5)
- coordinates = [(uniform(-100, 100), uniform(-100, 100)) for _ in range(NUMPTS)]
- xy = (uniform(-100, 100), uniform(-100, 100))
- # Common setup for all testcases (executed before any algorithm specific setup).
- COMMON_SETUP = dedent("""
- from __main__ import coordinates, xy
- """)
- class TestCase(namedtuple('CodeFragments', ['setup', 'test'])):
- """ A test case is composed of separate setup and test code fragments. """
- def __new__(cls, setup, test):
- """ Dedent code fragment in each string argument. """
- return tuple.__new__(cls, (dedent(setup), dedent(test)))
- testcases = {
- "schwobaseggl": TestCase("""
- dist = lambda x, y: (x[0]-y[0])**2 + (x[1]-y[1])**2
- """, """
- min(coordinates, key=lambda co: dist(co, xy))
- """
- ),
- "martineau (with hypot)": TestCase("""
- from math import hypot
- dist = lambda a, b: hypot(b[0]-a[0], b[0]-a[0])
- """, """
- min(coordinates, key=lambda co: dist(co, xy))
- """
- ),
- }
- # 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.
- print('Results for processing {:,d} points.'.format(NUMPTS))
- 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()
- """
- Results:
- Results for processing 10,000 points.
- Fastest to slowest execution speeds using Python 3.7.1
- (1,000 executions, best of 3 repetitions)
- martineau (with hypot) : 6.311196 secs, rel speed 1.00x, 0.00% slower
- schwobaseggl : 7.506378 secs, rel speed 1.19x, 18.94% slower
- """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement