{
"metadata": {
"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-final"
},
"orig_nbformat": 2,
"kernelspec": {
"name": "python3",
"display_name": "Python 3",
"language": "python"
}
},
"nbformat": 4,
"nbformat_minor": 2,
"cells": [
{
"source": [
"# Benchmarking and caching decorators\n",
"Let's say you have a really slow program and you want to benchmark where your program is taking most of the time to run. If you can find that you can just optimize that part of the program to run faster.\n",
"\n",
"There is couple of way of doing this going through this manually or using some kind of library like cProfile to generate a report on the function's workings.\n",
"\n",
"You can pretty much use this on any python function as you like, small-big-has other dependency anything.\n",
"\n",
"Let's see a few example as how to use these Benchmarking decorator."
],
"cell_type": "markdown",
"metadata": {}
},
{
"source": [
"from AKDSFramework.applications.decorators import benchmark"
],
"cell_type": "code",
"metadata": {},
"execution_count": 1,
"outputs": []
},
{
"source": [
"Now after importing we write a function and before the function we mention @benchmark and it'll generate reports of the innerworkings of the function.\n",
"\n",
"We gonna see an example of implementation of benchmarking by building a max heap and adding 2 numbers to the heap and again building it. To make max heaps I'll use AKDSFramework, let's create a heap and build it now with around 600 elements."
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
" 3597 function calls (3003 primitive calls) in 0.002 seconds\n\n Ordered by: cumulative time\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.002 0.002 :4(buildHeap)\n 2 0.000 0.000 0.002 0.001 /Users/royakash/Documents/GitHub/AKDSFramework/AKDSFramework/structure/heap.py:136(build)\n 1195/601 0.001 0.000 0.002 0.000 /Users/royakash/Documents/GitHub/AKDSFramework/AKDSFramework/structure/heap.py:155(heapify)\n 1195 0.000 0.000 0.000 0.000 /Users/royakash/Documents/GitHub/AKDSFramework/AKDSFramework/structure/heap.py:67(get_left_child)\n 1195 0.000 0.000 0.000 0.000 /Users/royakash/Documents/GitHub/AKDSFramework/AKDSFramework/structure/heap.py:53(get_right_child)\n 1 0.000 0.000 0.000 0.000 /Users/royakash/Documents/GitHub/AKDSFramework/AKDSFramework/structure/heap.py:128(__init__)\n 2 0.000 0.000 0.000 0.000 /Users/royakash/Documents/GitHub/AKDSFramework/AKDSFramework/structure/heap.py:26(add)\n 1 0.000 0.000 0.000 0.000 /Users/royakash/Documents/GitHub/AKDSFramework/AKDSFramework/structure/heap.py:21(__init__)\n 2 0.000 0.000 0.000 0.000 {built-in method builtins.len}\n 2 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n\n\n\n"
]
}
],
"source": [
"from AKDSFramework.applications.decorators import benchmark\n",
"from AKDSFramework.structure import MaxHeap\n",
"\n",
"@benchmark\n",
"def buildHeap(array):\n",
" h = MaxHeap(array)\n",
" h.build()\n",
"\n",
" h.add(68)\n",
" h.add(13)\n",
" h.build()\n",
"\n",
"buildHeap([data**2 for data in range(601)])"
]
},
{
"source": [
"Notice the @benchmark decorator at the beginning of the declaration of the function, that calls cProfile to start calculating what taking what.\n",
"\n",
"This has all the call's report and how much time it's taking. If you see the second last function call `{method 'append' of 'list' objects}` see that's called 2 times total as we are appending 2 elements.\n",
"\n",
"So this way you can see how much each function taking time and how many times they are called. If you wish you can reduce the number of calls or use a different approach to solve the part where it's slow."
],
"cell_type": "markdown",
"metadata": {}
},
{
"source": [
"## Caching\n",
"Now there is now way you can optimize the function, what you can do instead is that you can store results from a previous computation and reuse those results in a new computation to find solutions to other problem.\n",
"\n",
"Let's create world's worst fibonacci series computation code. The algorithm might look like this:\n",
"\n",
"```\n",
"FIBONACCI (n):\n",
" if n -> 0: f = 0\n",
" elif n -> 1: f = 1\n",
" else:\n",
" f = FIBONACCI(n - 1) + FIBONACCI (n - 2)\n",
" return f\n",
"```"
],
"cell_type": "markdown",
"metadata": {}
},
{
"source": [
"This is a correct algorithm for fibonacci. But if you see the recurrence relation T(n) = T(n-1) + T(n-2) + O(1) you can see that the code is running in exponential time O(2^N) which is really really bad.\n",
"\n",
"The equivalent python code would be:"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"def fibonacci(n):\n",
" if n == 0:\n",
" return 0\n",
" elif n == 1:\n",
" return 1\n",
" else:\n",
" return fibonacci(n - 1) + fibonacci(n - 2)"
]
},
{
"source": [
"If you draw a recursion tree you can find that you are computing same computation over and over again in different trees. Let's see what I mean:\n",
"\n",
"```\n",
"+--+-----------+-----------+--------+-----------+-----------+--+\n",
"| | | | Fib(n) | | | |\n",
"+--+-----------+-----------+--------+-----------+-----------+--+\n",
"| | | Fib (n-1) | | Fib (n-2) | | |\n",
"+--+-----------+-----------+--------+-----------+-----------+--+\n",
"| | Fib (n-2) | Fib (n-3) | | Fib (n-3) | Fib (n-4) | |\n",
"+--+-----------+-----------+--------+-----------+-----------+--+\n",
"```"
],
"cell_type": "markdown",
"metadata": {}
},
{
"source": [
"See for calculating fib(n) you are calculating Fib (n-1) and Fib (n-2). In a separate computation you are computing Fib (n-2) for that you are computing Fib (n-3) and Fib (n-4).\n",
"\n",
"If you had Fib (n-2) from the previous computation stored, you wouldn't have to recompute that Fib (n-2) and it's subsequent branches. So you would've saved a lot of time by just not recomputing anything.\n",
"\n",
"Let's without caching how much time it would take to compute fib(35) that is 35th fibonacci number:"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"9227465\nComputed in 4.039259026000025 seconds\n"
]
}
],
"source": [
"import time\n",
"\n",
"def fibonacci(n):\n",
" if n == 0:\n",
" return 0\n",
" elif n == 1:\n",
" return 1\n",
" return fibonacci(n - 1) + fibonacci(n - 2)\n",
"\n",
"\n",
"start = time.perf_counter()\n",
"print(fibonacci(35))\n",
"end = time.perf_counter()\n",
"\n",
"print(f\"Computed in {(end - start)} seconds\")"
]
},
{
"source": [
"Total time for computation is 4.039259026000025 seconds. So our python program is taking 4.039259026000025 seconds to compute fib(35). Now let's store intermediate step's data in a dictionary so that we can retrieve those data at a later time in constant time.\n",
"\n",
"First we import the caching decorator."
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"from AKDSFramework.applications.decorators import cached"
]
},
{
"source": [
"Now we write the function but with the caching decorator."
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"102334155\nComputed in 0.0004765559999668767 seconds\n"
]
}
],
"source": [
"import time\n",
"\n",
"@cached\n",
"def fibonacci(n):\n",
" if n == 0:\n",
" return 0\n",
" elif n == 1:\n",
" return 1\n",
" return fibonacci(n - 1) + fibonacci(n - 2)\n",
"\n",
"\n",
"start = time.perf_counter()\n",
"print(fibonacci(40))\n",
"end = time.perf_counter()\n",
"\n",
"print(f\"Computed in {(end - start)} seconds\")"
]
},
{
"source": [
"Now it takes around 0.0004765559999668767 seconds, which is a huge heap in performance."
],
"cell_type": "markdown",
"metadata": {}
}
]
}