Skip to content

Instantly share code, notes, and snippets.

@livibetter
Created July 4, 2017 06:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save livibetter/ec395e7ab1a050b3922790d2c3e8cfc6 to your computer and use it in GitHub Desktop.
Save livibetter/ec395e7ab1a050b3922790d2c3e8cfc6 to your computer and use it in GitHub Desktop.
element-wise addition on two lists
#!/usr/bin/env python3
from timeit import timeit
NUMBER = 1000
ELEMENTS = 10000
SETUP = 'N = {}; X = list(range(N)); Y = list(range(N))'.format(ELEMENTS)
SETUP_NP = 'N = {}; import numpy as np; X = np.arange(N); Y = np.arange(N)'.format(ELEMENTS)
STATS = [
['map with operator.add',
'list(map(add, X, Y))', SETUP + '; from operator import add'],
['map with lambda',
'list(map(add, X, Y))', SETUP + '; add = lambda x, y: x + y'],
['map with sum and zip',
'list(map(sum, zip(X, Y)))', SETUP],
['list comprehension with sum and zip',
'[sum(z) for z in zip(X, Y)]', SETUP],
['list comprehension with + and zip',
'[x + y for x, y in zip(X, Y)]', SETUP],
['numpy',
'X + Y', SETUP_NP],
]
NAME_WIDTH = max(len(stat[0]) for stat in STATS)
STAT_WIDTH = max(len(stat[1]) for stat in STATS)
print('With {:,} elements, average time of {:,} runs'.format(ELEMENTS, NUMBER))
for stat in STATS:
t = timeit(*stat[1:], number=NUMBER)
print('{:{name_width}}: {:{stat_width}} = {:7,.0f} us'.format(
stat[0], stat[1], t / NUMBER * 1000000,
name_width=NAME_WIDTH, stat_width=STAT_WIDTH))
#!/usr/bin/env python3
X = range(4)
Y = range(4)
from operator import add
OP_ADD = list(map(add, X, Y))
LAMBDA = list(map(lambda x, y: x + y, X, Y))
SUMZIP = list(map(sum, zip(X, Y)))
COMSUM = [sum(z) for z in zip(X, Y)]
COMZIP = [x + y for x, y in zip(X, Y)]
import numpy as np
AX = np.arange(4)
AY = np.arange(4)
NP_ADD = AX + AY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment