Skip to content

CHAPTER 1: The need for efficient coding I

How do we measure time?

import time

start_time = time.time()

result = 5 + 2

end_time = time.time()

print("Result calculated in {} sec".format(end_time - start_time))

For loop vs List comprehension

List comprehension:

import time

list_comp_start_time = time.time()
result = [i*i for i in range(1,1000000)]
list_comp_end_time = time.time()
print("Time using the list_comprehension: {} sec".format(list_comp_end_time - list_comp_start_time))

For loop:

import time

for_loop_start_time = time.time()
result = []
for i in range(0,1000000):
    result.append(i*i)
for_loop_end_time = time.time()
print("Time using the for loop: {} sec".format(for_loop_end_time - for_loop_start_time))
list_comp_time = list_comp_end_time - list_comp_start_time
for_loop_time = for_loop_end_time - for_loop_start_time
print("Difference in time: {} %".format((for_loop_time - list_comp_time) / list_comp_time * 100 ))

Where time matters Part 1

#Adding numbers one by one:
def sum_brute_force(N):
    res = 0
    for i in range(1,N+1):
        res+=1
    return res
#Using 1 + 2 + ... + N = N*(N+1)/2
def sum_formula(N):
    return N*(N+1)/2

Where time matters Part 2

#import time
import time

# Using the formula
formula_start_time = time.time()
formula_result = sum_formula(10000000)
formula_end_time = time.time()

print("Time using the formula: {} sec".format(formula_end_time - formula_start_time))
#import time
import time

#Using brute force
bf_start_time = time.time()
bf_result = sum_brute_force(1000000)
bf_end_time = time.time()

print("Time using brute force: {} sec".format(bf_end_time - bf_start_time))
formula_time = formula_end_time - formula_start_time
bf_time = bf_end_time - bf_start_time

print("Difference in speed: {} %".format((bf_time - formula_time) / formula_time * 100))