Last active
December 15, 2016 20:52
-
-
Save bhawkins/5095558 to your computer and use it in GitHub Desktop.
Check the performance of various ways of copying a numpy array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from __future__ import print_function | |
import timeit | |
import numpy as np | |
from distutils.version import StrictVersion | |
from six.moves import range | |
setup = """ | |
import numpy as np | |
from six.moves import range | |
n = 1000 | |
x = np.random.random(n) | |
y = np.empty_like(x) | |
""" | |
# These methods modify y so that all its values are equal to those in x. | |
methods = [ | |
"for i in range(n): y[i] = x[i]", | |
"y[:] = x" | |
] | |
if StrictVersion(np.__version__) >= StrictVersion('1.7.0'): | |
methods.append("np.copyto(y, x)") | |
# These methods create a new object y with values equal to those in x. | |
methods.extend( | |
""" | |
y = np.empty_like(x) | |
y[:] = x | |
# | |
y = np.empty(n) | |
y[:] = x | |
# | |
y = np.zeros_like(x) | |
y[:] = x | |
# | |
y = np.zeros(n) | |
y[:] = x | |
# | |
y = np.copy(x) | |
# | |
y = np.array(x) | |
# | |
y = 1*x | |
""".split('#\n') | |
) | |
niter = 10000 | |
for method in methods: | |
print(method.strip()) | |
print('Time =', timeit.timeit(method, setup=setup, number=niter)) | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment