A necessidade de codar com eficiência I

Escrevendo código eficiente com pandas

Leonidas Souliotis

PhD Researcher

Como medimos o tempo?

time.time(): retorna o horário atual em segundos desde 12:00 de 1º de janeiro de 1970

import time

# registrar tempo antes da execução start_time = time.time()
# executar operação result = 5 + 2
# registrar tempo após a execução end_time = time.time()
print("Result calculated in {} sec".format(end_time - start_time))
Result calculated in 9.48905944824e-05 sec
Escrevendo código eficiente com pandas

Loop for vs Compreensão de lista

  • Compreensão de lista:
    list_comp_start_time = time.time()
    result = [i*i for i in range(0,1000000)]
    list_comp_end_time = time.time()
    print("Time using the list_comprehension: {} sec".format(list_comp_end_time - 
    list_comp_start_time))
    
  • Loop for:
    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))
    
Escrevendo código eficiente com pandas

Loop for vs Compreensão de lista II

Time using the list comprehension: 0.11042404174804688 sec

Time using the for loop: 0.2071230411529541 sec
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))
Difference in time: 87.55527367398622 %
Escrevendo código eficiente com pandas

Onde o tempo importa I

Calcule $1+2+...+1000000$.

  • Somando número a número:
def sum_brute_force(N):
    res = 0
    for i in range(1,N+1):
        res+=i
    return res
  • Usando $\footnotesize 1 + 2 +... + N = \dfrac{N\cdot(N+1)}{2}$
def sum_formula(N):
    return N*(N+1)/2
Escrevendo código eficiente com pandas

Onde o tempo importa II

  • Usando a fórmula:
# Using the formula
formula_start_time = time.time()
formula_result = formula(1000000)
formula_end_time = time.time()

print("Time using the formula: {} 
sec".format(formula_end_time - formula_start_time))
Using the formula: 0.000108957290649 sec
  • Usando força bruta:
# 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 - start_time))
Time using brute force: 0.174870967865 sec
Difference in speed: 160,394.967179%
Escrevendo código eficiente com pandas

Vamos praticar!

Escrevendo código eficiente com pandas

Preparing Video For Download...