Time Complexity
To find the effectiveness of the program/algorithm, knowing how to evaluate them using Time complexity can make the program behave in required optimal conditions, and by doing so, it makes us efficient programmers.
Simple Time Module
There is a simple time module that just saves and subtracts the time before and after function execution! However, this method is imprecise since there may be a background process running that disturbs code execution, resulting in considerable differences in the running time of small code snippets.
Timeit Module
Timeit is easy to understand and has a command-line interface.
The module's built-in function timeit.timeit(stmt, setup, timer, number) takes four arguments.
Here we're analysing the Time complexity of Two very popular sorting Algorithms:
Here First I've created a random list using random module:
import random
li = list(range(101))
random.shuffle(li)
Now all you gotta do is create two variable stmt and setup and put code into it
1. Bubble-sort Algorithm
setup = '''
def bubble_sort_new(val):
swapped = False
for j in range(len(val)-1):
for i in range(len(val)-1-j):
if val[i] > val[i+1]:
val[i],val[i+1] = val[i+1],val[i]
swapped = True
if not swapped:
break
return val
'''
stmt = '''
val = [20,0,21,90,76,4,32,27,8,38,2,65,3,42,78,69,1,47,43,31,84,57,39,17,61,95,66,68,18,16,75,63,49,89,11,53,44,64,98,100,41,51,19,29,73,40,70,74,96,79,77,34,45,12,87,36,80,97,54,81,92,59,15,99,37,9,6,88,82,30,46,83,56,60,48,28,33,91,94,7,23,5,55,62,24,13,85,86,93,67,25,22,10,72,52,71,35,14,50,58,26]
bubble_sort_new(val)
'''
Now run; timeit.timeit(stmt,setup,number = 1000000) ----> this code now gonna run 1000000 times
The output is --->
509.6634564640008 sec.
2. Quick-Sort algorithm
setup = '''
def swap(a,b,arr):
if a!=b:
arr[a],arr[b] = arr[b],arr[a]
def partition(elements,start,end):
pivot_index = start
pivot = elements[pivot_index]
while start < end:
while start < len(elements) and elements[start] <= pivot:
start += 1
while elements[end] > pivot:
end-=1
if start < end:
swap(start,end,elements)
swap(pivot_index,end,elements)
return end
def quick_sort(elements, start, end):
if start < end:
pi = partition(elements, start, end)
quick_sort(elements, start, pi-1)
quick_sort(elements, pi+1, end)
'''
stmt = '''
elements = [20,0,21,90,76,4,32,27,8,38,2,65,3,42,78,69,1,47,43,31,84,57,39,17,61,95,66,68,18,16,75,63,49,89,11,53,44,64,98,100,41,51,19,29,73,40,70,74,96,79,77,34,45,12,87,36,80,97,54,81,92,59,15,99,37,9,6,88,82,30,46,83,56,60,48,28,33,91,94,7,23,5,55,62,24,13,85,86,93,67,25,22,10,72,52,71,35,14,50,58,26]
quick_sort(elements,0,len(elements)-1)
'''
Again run; timeit.timeit(stmt,setup,number = 1000000) ----> this code now gonna run 1000000 times
The output is --->
82.45940317699933 sec
Clearly Quick-sort algorithm is way fast then bubble-sort now you know which one to use.