Skip to content

Instantly share code, notes, and snippets.

@Magnus167
Created May 18, 2022 04:35
Show Gist options
  • Select an option

  • Save Magnus167/7b4409c0bfd1f0a88c0d167f2b11273a to your computer and use it in GitHub Desktop.

Select an option

Save Magnus167/7b4409c0bfd1f0a88c0d167f2b11273a to your computer and use it in GitHub Desktop.
experiments in python to compare speeds of functions that use loops vs loops within lists
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import random\n",
"RandInt = random.SystemRandom().randint\n",
"\n",
"def proc1(x):\n",
" sB, sA = 0, 0\n",
" for I in range(x):\n",
" sB, sA = I + 1, I\n",
" return sB\n",
" \n",
"\n",
"def proc2(x):\n",
" return [[I+1, I] for I in range(x)][-1][-1]\n",
"\n",
"def proc3(x):\n",
" s = 0\n",
" for I in range(x):\n",
" s += I\n",
" return s\n",
"\n",
"def proc4(x):\n",
" return sum([I for I in range(x)])"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"testIters = 10000"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.18 ms ± 48.5 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n"
]
}
],
"source": [
"timeit proc1(testIters)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2.01 ms ± 135 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n"
]
}
],
"source": [
"timeit proc2(testIters)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"969 µs ± 57.8 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n"
]
}
],
"source": [
"timeit proc3(testIters)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"738 µs ± 63.6 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n"
]
}
],
"source": [
"timeit proc4(testIters)"
]
}
],
"metadata": {
"interpreter": {
"hash": "82d133e37cc4ce819137925968dd7cc5b4ce9fca12643606578bb14597479d96"
},
"kernelspec": {
"display_name": "Python 3.9.12 ('jarphys2')",
"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.9.12"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment