Run Time Analysis
Simple Runtime Calculation with Python 3
When we are creating a solution for a problem we can be hindered by the efficiency of our solution.
A more efficient and well optimized code will run and solve the problem much faster than a less efficient code.
There are mathematical proofs / analysis you can do to your code to see the theoretical classification of your solution.
Currently this method is beyond the scope of the course, so we will only learn the classification not the proofs in a later lesson.
Using timeit
module
timeit
moduleWe will use a built-in python module called timeit
to help us calculate the runtime of our code.
Purpose:
We can compare multiple version of a solution if we have any
We can measure performance based on different parameters and inputs
This will help us test our code
Example Problem: Most Number of Factors
Look at numbers from
1 to N
;N being an integer greater than 1
.Calculate the number of factors of each N has
Output the number that created the largest factor
Unit & Refactoring Definitions
Unit: A segment of a program that handles a problem’s specific requirement.
Refactoring: The act of improving the performance and efficiency of the unit (section of a program) without affecting input and the output of the unit.
If a program is simplified to its Input → Processing → Output, then we are trying to optimize the “Processing” section of the program by Refactoring.
Refactoring: Most Number of Factors
This code is not the most efficient one, and we will make some optimizations to help it run faster.
A product of a number is pair of factors; therefore N = A * B where A and B are factors of N
If A is a Factor of N, then we can calculate B by N / A. This helps us a find two factors at once.
This way we also need to iterate our for loop only up to the Square Root of N.
If N is a perfect square, we can increase our count by 1 to denote that Square Root of N is a factor.
Yes, there are even more optimizations that can be done...
Last updated