Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # =====================================================================
- # map_method.py - A python-timeit-opts file
- # Copyright (C) 2019 Zach Carmichael
- #
- # This program is free software: you can redistribute it and/or modify
- # it under the terms of the GNU General Public License as published by
- # the Free Software Foundation, either version 3 of the License, or
- # (at your option) any later version.
- #
- # This program is distributed in the hope that it will be useful,
- # but WITHOUT ANY WARRANTY; without even the implied warranty of
- # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- # GNU General Public License for more details.
- #
- # You should have received a copy of the GNU General Public License
- # along with this program. If not, see <http://www.gnu.org/licenses/>.
- # =====================================================================
- from __future__ import absolute_import
- from __future__ import division
- from __future__ import print_function
- from __future__ import unicode_literals
- # noinspection PyCompatibility,PyUnresolvedReferences
- from builtins import (ascii, bytes, chr, dict, filter, hex, input,
- int, map, next, oct, open, pow, range, round,
- str, super, zip)
- import sys
- import random
- import timeit
- # noinspection PyUnresolvedReferences
- from operator import methodcaller
- import numpy as np
- import pandas as pd
- import seaborn as sns
- import matplotlib.pyplot as plt
- sns.set(style='whitegrid')
- def main_import(*args):
- if not args:
- return None
- return '\n'.join('from __main__ import {}'.format(arg) for arg in args)
- class DummyNum(object):
- """Dummy class"""
- __slots__ = 'n',
- def __init__(self, n):
- self.n = n
- def add(self):
- self.n += 5
- # Dict for product codes
- map_codes = dict(
- map_lambda=(
- 'list(map(lambda x: x.add(), vals))',
- None),
- map_operator=(
- 'list(map(methodcaller("add"), vals))',
- ('methodcaller',)),
- map_comprehension=(
- '[x.add() for x in vals]',
- None),
- )
- if len(sys.argv) > 1:
- if len(sys.argv) > 2:
- self_name = globals().get('__file__', # Option 1
- locals().get('__file__', # Option 2
- __name__)) # Option 3
- sys.exit('Usage: {} [filename]'.format(self_name))
- filename = sys.argv[1]
- else:
- filename = None
- if filename is None:
- max_int = np.iinfo(np.int64).max
- # Array sizes
- N = 50
- sizes = np.logspace(0, 8, N, dtype=int)
- repeats = np.logspace(4, 1, N, dtype=int)
- # Result storage
- results = []
- # Begin heavy lifting
- print('Python', sys.version)
- for array_size, repeat in zip(sizes, repeats):
- # Generate numbers (+1 as edge is non-inclusive)
- # Generate array_size numbers in range [-max_int - 1, max_int)
- def gen_ints():
- return [random.randint(-max_int - 1, max_int + 1)
- for _ in range(array_size)]
- int_vals = gen_ints()
- float_vals = list(map(float, int_vals))
- # Cast 1st set to DummyNum
- int_vals = list(map(DummyNum, int_vals))
- float_vals = list(map(DummyNum, float_vals))
- # Evaluate each method, record results
- for k_meth, (v_meth_code, v_meth_setup) in map_codes.items():
- if not isinstance(v_meth_code, (list, tuple)):
- v_meth_code = (v_meth_code, v_meth_code,)
- # Evaluate each dtype
- for v_meth_code_dtype, dtype in zip(v_meth_code, ['int', 'float']):
- print('Timing {} with {}s for size {}'.format(
- k_meth, dtype, array_size))
- v_meth_setup = v_meth_setup if v_meth_setup else tuple()
- time_result = timeit.timeit(
- v_meth_code_dtype,
- setup=main_import('{}_vals as vals'.format(dtype),
- *v_meth_setup),
- number=repeat
- )
- results.append(dict(
- method=k_meth,
- time=time_result,
- dtype=dtype,
- size=array_size,
- ))
- # Plot results
- py_v = sys.version_info
- py_v_str = 'python{}.{}.{}'.format(py_v.major, py_v.minor, py_v.micro)
- df = pd.DataFrame(results)
- df.to_csv('timeit_map_method_' + py_v_str + '.csv', index=False)
- else:
- df = pd.read_csv(filename)
- dash_styles = [
- '',
- (4.0, 1.5),
- (1.0, 1.0),
- (3.0, 1.0, 1.5, 1.0),
- (5.0, 1.0, 1.0, 1.0),
- (5.0, 1.0, 2.0, 1.0, 2.0, 1.0),
- (2.0, 2.0, 3.0, 1.5),
- (1.0, 2.5, 3.0, 1.2),
- (1.0, 1.0, 1.0, 1.0, 1.0, 1.5, 5.0, 1.5),
- (4.0, 1.5, 1.0, 1.0, 1.0, 1.0),
- (2.0, 2.0, 1.0, 1.0),
- ]
- g = sns.relplot(x='size', y='time', hue='method', style='method', col='dtype',
- kind='line', data=df, dashes=dash_styles)
- for ax in g.axes.flat:
- ax.set_xscale('log')
- ax.set_yscale('log')
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement