Skip to content

Instantly share code, notes, and snippets.

@nopdotcom
Created August 30, 2021 19:40
Show Gist options
  • Save nopdotcom/fecf1b52324a126df06622c3f3133f7a to your computer and use it in GitHub Desktop.
Save nopdotcom/fecf1b52324a126df06622c3f3133f7a to your computer and use it in GitHub Desktop.
Microbenchmarking iterative vs functional style
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "naked-scholarship",
"metadata": {},
"outputs": [],
"source": [
"alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n",
"str_user_title = \"Technologist\"\n",
"ODDS_OF_CORRECT_TITLE = 50\n",
"NUM_RECORDS = 1000\n",
"\n",
"import random\n",
"def random_title():\n",
" if random.randint(0, ODDS_OF_CORRECT_TITLE) == 0:\n",
" return str_user_title\n",
" else:\n",
" return \"\".join(random.choices(alphabet, k=5))\n",
"def random_record():\n",
" return dict(title=random_title(), foo=0, bar=1, baz=2, quux=3)\n",
"\n",
"random.seed(0)\n",
"random_records = [random_record() for x in range(NUM_RECORDS)]\n",
"ptr_DictReader = random_records"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "urban-bottle",
"metadata": {},
"outputs": [],
"source": [
"# This should always return the same result:\n",
"assert random_records[1]['title'] == \"vzjxf\""
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "innovative-investing",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"32.6 µs ± 158 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n"
]
}
],
"source": [
"%%timeit \n",
"int_counter=0\n",
"for it_row in ptr_DictReader:\n",
" if it_row['title'] == str_user_title:\n",
" int_counter += 1"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "flexible-winter",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"47.8 µs ± 77.8 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n"
]
}
],
"source": [
"%%timeit\n",
"sum(it_row[\"title\"] == str_user_title for it_row in ptr_DictReader)"
]
}
],
"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.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment