[test] python list comprehension

mgm-dev·2020년 11월 28일
0
post-thumbnail

📚TL;DR

list comprehension은 syntax sugar가 아니다


x * 2 반복하는 경우

%matplotlib inline
import matplotlib.pyplot as plt
import timeit
def multiply(x):
     return x * 2

max_iter = 10000
delta_iter = 1000
x = range(delta_iter, max_iter, delta_iter)
x1 = [i/1000 for i in x]
y1 = []
y2 = []

for i in x:
    time1 = timeit.default_timer()    
    multiples_of_two = []
    for j in range(0, i):
         multiples_of_two.append(multiply(j))
    time2 = timeit.default_timer()
        
    delta_time1 = 1000 * (time2 - time1)
    y1.append(delta_time1)
    
    time10 = timeit.default_timer()      
    multiples_of_two = [multiply(j) for j in range(0, i)]
    time20 = timeit.default_timer()
        
    delta_time2 = 1000 * (time20 - time10)
    y2.append(delta_time2)
    

plt.plot(x1, y1, color='red', label= "For-loop")
plt.plot(x1, y2, color='blue', label= "List-compr")
plt.xlabel("iter")
plt.ylabel('ms')

plt.show


x ** x 반복하는 경우

%matplotlib inline
import matplotlib.pyplot as plt
import timeit
def exponent(x):
     return x ** x

max_iter = 1000
delta_iter = 100
x = range(delta_iter, max_iter, delta_iter)
x1 = [i/1000 for i in x]
y1 = []
y2 = []

for i in x:
    time1 = timeit.default_timer()    
    multiples_of_two = []
    for j in range(0, i):
         multiples_of_two.append(exponent(j))
    time2 = timeit.default_timer()
        
    delta_time1 = 1000 * (time2 - time1)
    y1.append(delta_time1)
    
    time10 = timeit.default_timer()      
    multiples_of_two = [exponent(j) for j in range(0, i)]
    time20 = timeit.default_timer()
        
    delta_time2 = 1000 * (time20 - time10)
    y2.append(delta_time2)
    

plt.plot(x1, y1, color='red', label= "For-loop")
plt.plot(x1, y2, color='blue', label= "List-compr")
plt.xlabel("iter")
plt.ylabel('ms')

plt.show

profile
never stop learning

0개의 댓글