Skip to content

Instantly share code, notes, and snippets.

@termoshtt
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save termoshtt/824ff3e766de5fe9fdd6 to your computer and use it in GitHub Desktop.
Save termoshtt/824ff3e766de5fe9fdd6 to your computer and use it in GitHub Desktop.
Numba_sample.ipynb
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n",
"import numba"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"a = np.random.randn(200, 200)\n",
"b = np.random.randn(200, 200)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def matmul1(a, b):\n",
" lenI = a.shape[0]\n",
" lenJ = a.shape[1]\n",
" lenK = b.shape[1]\n",
" c = np.zeros((lenI, lenJ))\n",
" for i in range(lenI):\n",
" for j in range(lenJ):\n",
" for k in range(lenK):\n",
" c[i, j] += a[i, k] * b[k, j]\n",
" return c"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"@numba.jit\n",
"def matmul1_jit(a, b):\n",
" lenI = a.shape[0]\n",
" lenJ = a.shape[1]\n",
" lenK = b.shape[1]\n",
" c = np.zeros((lenI, lenJ))\n",
" for i in range(lenI):\n",
" for j in range(lenJ):\n",
" for k in range(lenK):\n",
" c[i, j] += a[i, k] * b[k, j]\n",
" return c"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"c = matmul1_jit(a, b) # 初回は遅いので回避"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 loops, best of 3: 12.9 s per loop\n"
]
}
],
"source": [
"%timeit matmul1(a, b)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10 loops, best of 3: 24.4 ms per loop\n"
]
}
],
"source": [
"%timeit matmul1_jit(a, b)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10 loops, best of 3: 20.7 ms per loop\n"
]
}
],
"source": [
"%timeit np.dot(a, b)"
]
}
],
"metadata": {
"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.10"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment