{ "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" }, "collapsed": false, "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" }, "collapsed": false, "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" }, "collapsed": false, "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))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "celltoolbar": "Slideshow", "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.12" }, "latex_envs": { "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": false, "eqNumInitial": 0 }, "toc": { "toc_cell": false, "toc_number_sections": true, "toc_threshold": 6, "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 0 }