Skip to content

Instantly share code, notes, and snippets.

@synapticarbors
Last active February 11, 2016 21:43
Show Gist options
  • Save synapticarbors/7764ee423779d50fc671 to your computer and use it in GitHub Desktop.
Save synapticarbors/7764ee423779d50fc671 to your computer and use it in GitHub Desktop.
Example of numba codegen from string
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"import numba as nb"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def gen_code(p1, p2, verbose=False):\n",
" code_template = '''\\\n",
"def func(x):\n",
" s = {p1} * x[0]\n",
" for k in xrange(1, x.shape[0]):\n",
" s += {p2} * x[k]\n",
"\n",
" return s\n",
"'''\n",
"\n",
" code_str = code_template.format(**dict(p1=p1, p2=p2)).strip()\n",
" if verbose:\n",
" print code_str\n",
"\n",
" localf = {}\n",
" code = compile(code_str, '<>', 'exec')\n",
" eval(code, localf)\n",
"\n",
" return localf['func']"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"def func(x):\n",
" s = 3.0 * x[0]\n",
" for k in xrange(1, x.shape[0]):\n",
" s += 6.0 * x[k]\n",
"\n",
" return s\n"
]
}
],
"source": [
"func = gen_code(3.0, 6.0, verbose=True)\n",
"fastfunc = nb.jit(nopython=True)(func)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"27.0"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"func(np.ones(5))"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"27.0\n"
]
}
],
"source": [
"print fastfunc(np.ones(5))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"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.11"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment