{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## How much faster vectorized computation with Numpy is comparing to loops in python?\n", "\n", "### The notebook / example from:\n", "https://python.plainenglish.io/vectorized-and-non-vectorized-mathematical-computations-a9f7a7846a01\n", "\n", "### Copyright belongs to the originial author of this post.\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "import time\n", "import numpy as np" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "\n", "x1 = np.random.randint(low=11, high=99, size=100000)\n", "x2 = np.random.randint(low=11, high=99, size=100000)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Comparison about he dot product of two vectors" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Computation time = 66.12992286682129\n", "Computation time = 0.1919269561767578\n" ] } ], "source": [ "# CLASSIC DOT VECTORS IMPLEMENTATION\n", "tic = time.time()\n", "dot = 0\n", "for i in range(len(x1)):\n", " dot+= x1[i]*x2[i]\n", "toc = time.time()\n", "print(\"Computation time = \",1000*(toc - tic))\n", "\n", "# VECTORIZED DOT IMPLEMENTATION\n", "tic = time.time()\n", "dot = np.dot(x1,x2)\n", "toc = time.time()\n", "print(\"Computation time = \",1000*(toc - tic))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### How about matrix-vector multiplication?" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Computation time = 286.9250774383545\n", "Computation time = 0.9779999999999234\n" ] } ], "source": [ "\n", "# CLASSIC GENERAL DOT IMPLEMENTATION\n", "W = np.random.rand(3,len(x1)) # Random 3*len(x1) numpy array\n", "tic = time.time()\n", "gdot = np.zeros(W.shape[0])\n", "for i in range(W.shape[0]):\n", " for j in range(len(x1)):\n", " gdot[i] += W[i,j]*x1[j]\n", "toc = time.time()\n", "print(\"Computation time = \",1000*(toc - tic))\n", "\n", "# VECTORIZED GENERAL DOT IMPLEMENTATION\n", "tic = time.process_time()\n", "dot = np.dot(W,x1)\n", "toc = time.process_time()\n", "print(\"Computation time = \",1000*(toc - tic))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.5" } }, "nbformat": 4, "nbformat_minor": 4 }