언어 Language/파이썬 Python

Q. Python에서 함수나 구문의 속도를 측정하는 방법은?

Tap to restart 2023. 4. 29. 15:00
반응형

A. cProfile을 이용해서 측정할 수 있다.

출처: 파이썬 프로파일러
 
 

인라인 리스트 예

아래 같은 코드를 추가하고 실행해보자.

import cProfile

def get_number_list():
    number_list = []
    for i in range(1000000):
        number_list.append(i)
    return number_list

cProfile.run(statement="get_number_list()")
cProfile.run(statement="[i for i in range(1000000)]")

 
실행결과 
 

같은 숫자 배열을 얻는 경우인데, 인라인으로 처리한 경우가 약 4배 빠른 것을 확인할 수 있다.
 

not A and not B와 not (A or B) 비교 예

not A and not B = not (A or B)는 같다. 고등학교 수학 시간에 배우는 드모르간 법칙이다.
속도는 얼마나 차이가 날까? cProfile을 통해서 비교해 볼 수 있다.

import cProfile

A = True
B = False

def not_a_and_not_b():
    result = []
    for i in range(1000000):
        result.append(not A and not B)
    return result

def not_a_or_b():
    result = []
    for i in range(1000000):
        result.append(not (A or B))
    return result

def not_a_or_not_b():
    result = []
    for i in range(1000000):
        result.append(not A or not B)
    return result

def not_a_and_b():
    result = []
    for i in range(1000000):
        result.append(not (A and B))
    return result

cProfile.run(statement="not_a_and_not_b()")
cProfile.run(statement="not_a_or_b()")
cProfile.run(statement="not_a_or_not_b()")
cProfile.run(statement="not_a_and_b()")

두 경우를 비교해 봤을 때 유의미한 차이는 없었다.
 

 
위 예들처럼 같은 결과를 얻는 두 코드의 속도차가 궁금할 때 활용할 수 있다.
 
 

반응형