Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save brianspiering/d7b18981ce1f6b8e3e246421ed090c7f to your computer and use it in GitHub Desktop.
Save brianspiering/d7b18981ce1f6b8e3e246421ed090c7f to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"toc": true
},
"source": [
"<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n",
"<div class=\"toc\"><ul class=\"toc-item\"></ul></div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's benchmark operator vs method for Counter updates"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [],
"source": [
"from collections import Counter\n",
"import random\n",
"from string import ascii_letters as letters"
]
},
{
"cell_type": "code",
"execution_count": 100,
"metadata": {},
"outputs": [],
"source": [
"# Setup\n",
"old_counts = Counter()\n",
"\n",
"new_counts = {''.join(random.choices(letters, k=10)): random.randint(1, 100) for _ in range(1_000_000)}"
]
},
{
"cell_type": "code",
"execution_count": 102,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"463 ms ± 10.6 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%%timeit -n 10\n",
"\n",
"global old_counts # Must be global for benchmarking\n",
"old_counts += new_counts # Operator"
]
},
{
"cell_type": "code",
"execution_count": 103,
"metadata": {},
"outputs": [],
"source": [
"# Reset for fair benchmarking\n",
"old_counts = Counter()"
]
},
{
"cell_type": "code",
"execution_count": 104,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"409 ms ± 20.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
]
}
],
"source": [
"%%timeit -n 10\n",
"\n",
"old_counts.update(new_counts) # Method"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We have a winner - method\n",
"\n",
"It is clear that the `update` method is a faster way to update Counters."
]
}
],
"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.8.3"
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": false,
"sideBar": false,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": true,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment