Skip to content

Instantly share code, notes, and snippets.

@jtratner
Last active December 21, 2015 18:29
Show Gist options
  • Save jtratner/6348097 to your computer and use it in GitHub Desktop.
Save jtratner/6348097 to your computer and use it in GitHub Desktop.
Comparing cost of function calls [ipython-notebook]
Display the source blob
Display the rendered blob
Raw
{
"metadata": {
"name": "Comparing cost of function calls"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": "def without_func_call(arr):\n out = []\n for i, elem in enumerate(arr):\n if i % 3 == 0:\n out.append(5)\n else:\n out.append(elem)\n return out\n\ndef func(i, elem):\n if i % 3 == 0:\n return 5\n else:\n return elem\n \ndef with_func_call(arr):\n out = []\n for i, elem in enumerate(arr):\n out.append(func(i, elem))\n return out\n ",
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": "arr = range(100)\narr2 = range(1000)\narr3 = range(10000)\nprint \"100 length\"\n%timeit without_func_call(arr)\n%timeit with_func_call(arr)\nprint \"1000 length\"\n%timeit without_func_call(arr2)\n%timeit with_func_call(arr2)\nprint \"10000 length\"\n%timeit without_func_call(arr3)\n%timeit with_func_call(arr3)",
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": "100 length\n10000 loops, best of 3: 42.5 us per loop"
},
{
"output_type": "stream",
"stream": "stdout",
"text": "\n10000 loops, best of 3: 58.3 us per loop"
},
{
"output_type": "stream",
"stream": "stdout",
"text": "\n1000 length\n1000 loops, best of 3: 372 us per loop"
},
{
"output_type": "stream",
"stream": "stdout",
"text": "\n1000 loops, best of 3: 521 us per loop"
},
{
"output_type": "stream",
"stream": "stdout",
"text": "\n10000 length\n100 loops, best of 3: 3.73 ms per loop"
},
{
"output_type": "stream",
"stream": "stdout",
"text": "\n100 loops, best of 3: 5.21 ms per loop"
},
{
"output_type": "stream",
"stream": "stdout",
"text": "\n"
}
],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": "print \"Finished\"",
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": "Finished\n"
}
],
"prompt_number": 4
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment