2020 Chapter 008. PROGRAM EFFICIENCY
2020 Chapter 008. PROGRAM EFFICIENCY
EFFICIENCY
Measuring the performance
Introduct
ion
Efficiency refers to the quality of Algorithm
i.e. code must perform the task in
minimum execution time and resources.
It is important to measure the efficiency of
algorithm before applying them on large
scale i.e. on bulk of data.
Nowadays most of application are online
where prompt response is required, if
efficiency of algorithm is not checked then
the site will crash and organization may
loose their customer/business because of
slow speed.
Introduct
ion
The performance of Algorithm depends
upon
INTERNAL FACTORS
Time Required to Run
Space(or Memory) required to Run
EXTERNAL FACTORS
Size of input to the algorithm
Speed of the computer on which it is run
Quality of the compiler.
COMPLEXIT
Y
n2 100 400 1600 10000 160000
Consecutive statements
If-then-else statements
Logarithmic complexity
Loo
p
The running time of loop is equal to the
running time of statements inside the
loopof multiplied by numberLoop
iteration. For
execute
example: for i in s n
times
range(n): All the
steps in
a=a+2 this loop
takesC
So, total time taken = C * n = Cnconstant
,
time,
here n is a
dominant term, So efficiency is O(n)
Nested
Loop
To compute complexity of nested loop,
analyze inside out. For nested loops,
total
product running
of thetime
sizesisof
the
Outer
loops: for i in loop n
times
range(n):
takes for j in range(n):
S=S+ Inner
All steps
constant loop n
time C
1 times
Constant time C7
So total time taken will be : C1+C2+
(C3+C4)*n+C5+C6+C7 i.e O(n), considering
the dominant term which is n
Determining the complexity of
a program that checks if a
Second approach 𝑛
number n is prime
𝑎𝑝𝑝𝑟𝑜𝑎𝑐ℎ
Constant Time C1
Constant Time C2
Constant time C3
Loop repeats 𝑛
times
Constant time C4
Constant time C5
Constant time C6
Constant time C7
def
linearSearch(mylist,ite
m): Loop repeats n
n= times
Constant time C2
len(mylist)
for i in Constant time C3
range(n):
Constant time C4
if item
So total time taken : C1 + (C2+C3) * n
+ C4 i.e. O(n) ==
mylist[
Only dominant term is taken
i]:
return
Determining the complexity of
a program that searches for
an element in array
Option 2 : Binary
C1 Search C4
C2 C C5
Low<=high
: 3
Loop C6
repeats C7
max log2N
times C8
because
every time C9
segment
becomes C10
Sohalftotal
in time taken :
C1+C2+log2N(C3+C4+…C10)
size i.e.
O(log2N)
How many times above
while loop executes?
How many times can you divide N by 2 until you have 1?
This is because in binary searching, search begins with N
and reduces to its half after every iteration and stops
when the search segment size reduce to 1 element. So if
loop repeats k times then in formula this would be:
N/2k =
1 2k =
N
Taking log2 on both
sides:
log2(2k) = log2N
k * log2(2) =
log2N k * 1 =
log2N
k = log2N
This means you can divide log N times until you have
everything divided this means loops repeats at max log N