{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Vectorize\n", "============" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import numpy as np\n", "a = np.random.uniform(size=10000)\n", "b = np.random.uniform(size=10000)\n", "%time c = a + b\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "def add_vectors(first, second):\n", " a = np.empty(first.shape)\n", " for i in xrange(len(first)):\n", " a[i] = first[i] + second[i]\n", " " ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "%time c = add_vectors(a, b)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Don't write for-loops!\n", "------------------------\n", "\n", "If you can't avoid it (writing your custom algorithms)\n", "Use Cython\n", "===========" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%load_ext cythonmagic" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "%%cython\n", "\n", "import numpy as np\n", "cimport numpy as np\n", "\n", "def add_vectors_fast(first, second):\n", " a = np.empty(first.shape)\n", " for i in xrange(len(first)):\n", " a[i] = first[i] + second[i]\n", " return a\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "%time c = add_vectors_fast(a, b)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "%%cython\n", "\n", "cimport cython\n", "cimport numpy as np\n", "\n", "#@cython.boundscheck(False)\n", "#@cython.wraparound(False)\n", "def add_vectors_fast2(double[:] first, double[:] second):\n", " cdef np.ndarray[double, ndim = 1, mode = \"c\"] a = np.ndarray(first.shape[0])\n", " #cdef int i\n", " for i in range(len(first)):\n", " a[i] = first[i] + second[i]\n", " return a\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "%time c = add_vectors_fast2(a, b)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }