Created
November 7, 2018 12:39
-
-
Save ahartikainen/1f9db8d98f64d22b8954a639ca9744c8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"import numpy as np\n", | |
"from collections import OrderedDict\n", | |
"from operator import itemgetter" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 2, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"Wall time: 309 ms\n" | |
] | |
} | |
], | |
"source": [ | |
"%time key_vars = OrderedDict({str(key) : np.array([key, key, key], dtype=np.float64) for key in np.random.choice(np.arange(0,1_000_000), 100_000, replace=False)})" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 3, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"def create_array(gen, shape, dtype):\n", | |
" arr = np.empty(shape, dtype=dtype)\n", | |
" for i, val in enumerate(gen):\n", | |
" arr[i] = val\n", | |
" return arr" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 4, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"43.7 ms ± 1.28 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n", | |
"56.3 ms ± 3.01 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n", | |
"45.1 ms ± 1.46 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n" | |
] | |
} | |
], | |
"source": [ | |
"# select a subset of keys (this case, use all)\n", | |
"keys = list(key_vars.keys())\n", | |
"# naive method\n", | |
"%timeit arr0 = np.array([key_vars[key] for key in keys], dtype=np.float64)\n", | |
"\n", | |
"# iter over generator\n", | |
"%timeit arr2 = create_array((key_vars[key] for key in keys), (len(keys), 3), np.float64)\n", | |
"\n", | |
"# use itemgetter\n", | |
"%timeit arr1 = np.array(itemgetter(*keys)(key_vars), dtype=np.float64)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": [] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Python 3", | |
"language": "python", | |
"name": "python3" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": "3.7.0" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment