Skip to content

Instantly share code, notes, and snippets.

@PM2Ring
Created June 8, 2017 10:49
Show Gist options
  • Save PM2Ring/a4d0540f960a80fde91fa808eaa88700 to your computer and use it in GitHub Desktop.
Save PM2Ring/a4d0540f960a80fde91fa808eaa88700 to your computer and use it in GitHub Desktop.
Compare the speed of zip with various Numpy stack functions
#!/usr/bin/env python3
''' Compare the speeds of zip and various Numpy functions
for stacking to 1D Numpy arrays into a 2D array
See https://stackoverflow.com/q/44409084/4014959
Written by PM 2Ring 2017.06.08
'''
import numpy as np
from timeit import Timer
cmds = {
'column': 'np.column_stack((a, b))',
'dstack': 'np.dstack((a, b))',
'stack': 'np.stack((a, b), axis=-1)',
'zip': 'np.array(list(zip(a, b)))',
}
loops = 1000
setup = 'from __main__ import np, a, b'
for i in range(10):
n = 1 << i
a = np.arange(1, n + 1)
b = np.arange(n + 1, 2*n + 1)
print('\nSize:', n)
timings = []
for name, cmd in cmds.items():
t = Timer(cmd, setup)
result = sorted(t.repeat(3, loops))
timings.append((result, name))
timings.sort()
for result, name in timings:
print('{:<6} : {}'.format(name, result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment