2017-11-07 7 views
0

나는 계산을 통해 값을 10000-1000000 번 반복하고 그 출력의 일부를 목록에 추가해야하는 그래프 작성 프로그램을 만들고 있습니다. 추가되는 목록을 변경하기 위해 루프 내에 ~ 3 개의 if 문이 있습니다. 논리적으로 if 문을 먼저 사용하는 것이 논리적으로 빠르지 만 상당한 시간을 절약 할 수 있습니까?if 문이 파이썬에서 상당한 시간이 걸립니까?

output = [] 
append_to = "pol" 
if append_to == "pol": 
    for i in range(10000): 
     output.append(np.cos(i)) 
else: 
    for i in range(10000): 
     output.append(np.sin(i)) 
+0

더 빠르지 만 완전히 동등하지 않다는 것을 명심하십시오. ('append_to'의 값이 변할 수 있다고 가정하면 그렇지 않습니다.) – DeepSpace

+1

전체 루프 동안 'append_to'가 동일하게 유지됩니까? 이 경우, append_to == "pol"else np.sin'을 정의한 다음 'output = list (map (f, range (10000))'를 수행 할 수 있습니다. –

+0

예, append_to는 동일하게 유지됩니다 전체 루프에서 왜 이것이 질문을 무효화합니까? 최적화에 대해 묻습니다. 제안 해 주셔서 감사합니다.지도 기능을 살펴보아야합니다. –

답변

2

왜 그냥 시도 해달라고 :

output = [] 
append_to = "pol" 
for i in range(10000): 
    if append_to == "pol": 
     output.append(np.cos(i)) 
    else: 
     output.append(np.sin(i)) 

이이보다 훨씬 느린 될 것이다 : 예를 들어

?

import numpy as np 
import timeit 

def one(): 
    output = [] 
    append_to = "pol" 
    for i in range(10000): 
     if append_to == "pol": 
      output.append(np.cos(i)) 
     else: 
      output.append(np.sin(i)) 

def two(): 
    output = [] 
    append_to = "pol" 
    if append_to == "pol": 
     for i in range(10000): 
      output.append(np.cos(i)) 
    else: 
     for i in range(10000): 
      output.append(np.sin(i)) 

print(timeit.timeit('f()', 'from __main__ import one as f', number=1000)) 
print(timeit.timeit('f()', 'from __main__ import two as f', number=1000)) 

Output: 
9.042721510999854 
8.626055914000062 

예, 예상보다 빠릅니다. 또한 조회가 약간의 시간이 걸린다는 것을 알고 있기 때문에 ap = output.append을 수행 한 다음 대신 output.append을 호출하면 한계가 개선됩니다.

2

사용해보기!

import math, time 

time_start = time.time() 

output = [] 
append_to = "pol" 
for i in range(10000000): 
    if append_to == "pol": 
     output.append(math.cos(i)) 
    else: 
     output.append(math.sin(i)) 

print("End: " + str(time.time() - time_start)) 

실행하려면 4.278s가 있어야합니다. 이 실행의 경우 :

import math, time 

time_start = time.time() 

output = [] 
append_to = "pol" 
if append_to == "pol": 
    for i in range(10000000): 
     output.append(math.cos(i)) 
else: 
    for i in range(10000000): 
     output.append(math.sin(i)) 

print("End: " + str(time.time() - time_start)) 

나는 3.751 초가 있습니다.

그래서 가자!