{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": "## A primer to vector computing" }, { "cell_type": "markdown", "metadata": {}, "source": "### Multidimensional arrays" }, { "cell_type": "markdown", "metadata": {}, "source": "### The ndarray" }, { "cell_type": "markdown", "metadata": {}, "source": "### Vector operations on ndarrays" }, { "cell_type": "markdown", "metadata": {}, "source": "### Example: how fast are vector computations in NumPy?" }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": "from random import random\nlist_1 = [random() for _ in range(1000000)]\nlist_2 = [random() for _ in range(1000000)]" }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": "[0.843375384328939, 1.507485612134079, 1.4119777108063973]" }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": "out = [x + y for (x, y) in zip(list_1, list_2)]\nout[:3]" }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": "10 loops, best of 3: 69.7 ms per loop" }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": "%timeit [x + y for (x, y) in zip(list_1, list_2)]" }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": "import numpy as np\narr_1 = np.array(list_1)\narr_2 = np.array(list_2)" }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": "(list, numpy.ndarray)" }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": "type(list_1), type(arr_1)" }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": "(1000000,)" }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": "arr_1.shape" }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": "dtype('float64')" }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": "arr_1.dtype" }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": "array([ 0.84337538, 1.50748561, 1.41197771])" }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": "sum_arr = arr_1 + arr_2\nsum_arr[:3]" }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": "1000 loops, best of 3: 1.57 ms per loop" }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": "%timeit arr_1 + arr_2" }, { "cell_type": "markdown", "metadata": {}, "source": "### How an ndarray is stored in memory" }, { "cell_type": "markdown", "metadata": {}, "source": "### Why operations on ndarrays are fast" } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 0 }