{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Python performance optimization" ] }, { "cell_type": "markdown", "metadata": { "ExecuteTime": { "end_time": "2017-01-28T11:29:43.100718", "start_time": "2017-01-28T11:29:43.009165" }, "slideshow": { "slide_type": "slide" } }, "source": [ "## Membership testing is faster in dict than in list. \n", "\n", "Python dictionaries use hash tables, this means that a lookup operation (e.g., if x in y) is O(1). A lookup operation in a list means that the entire list needs to be iterated, resulting in O(n) for a list of length n. http://www.clips.ua.ac.be/tutorials/python-performance-optimization" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2017-02-25T15:32:34.036617", "start_time": "2017-02-25T15:32:34.028978" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "import timeit\n", "def test_ifin(d):\n", " if 5000 in d:\n", " a = 1\n", " else:\n", " a = 2\n", "\n", "d1 = dict.fromkeys(range(10000), True)\n", "d2 = range(10000)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2017-02-25T15:32:44.772804", "start_time": "2017-02-25T15:32:44.700130" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.000880002975464\n", "0.0672550201416\n" ] } ], "source": [ "print (timeit.timeit(lambda: test_ifin(d1), number=1000))\n", "print (timeit.timeit(lambda: test_ifin(d2), number=1000))" ] } ], "metadata": { "celltoolbar": "Slideshow", "kernel_info": { "name": "python3" }, "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.3" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autoclose": false, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": false, "eqNumInitial": 0, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false }, "nteract": { "version": "0.14.3" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": false, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 1 }