Python for Beginners
16.1 프로파일링
Records that rule memory
2023. 5. 8. 10:18
728x90
프로파일링은 코드의 실행 시간과 메모리 사용량을 측정하여 성능을 분석하고 최적화할 수 있는 도구입니다. 파이썬에서는 내장된 `cProfile`, `profile`, `timeit` 모듈 등을 사용하여 프로파일링을 수행할 수 있습니다. 또한, `memory_profiler`와 같은 외부 라이브러리도 사용할 수 있습니다.
1. `cProfile`: `cProfile`은 파이썬의 표준 프로파일러로, 함수 호출 횟수와 각 함수의 실행 시간을 측정할 수 있습니다.
예시코드:
import cProfile
import re
def example_function():
s = 0
for i in range(10000):
s += i
return s
def main():
example_function()
cProfile.run('main()')
2. `timeit`: `timeit` 모듈은 작은 코드 조각의 실행 시간을 측정하는 데 유용합니다. 코드를 여러 번 실행하여 평균 실행 시간을 구할 수 있습니다.
예시코드:
import timeit
def example_function():
s = 0
for i in range(10000):
s += i
return s
execution_time = timeit.timeit('example_function()', 'from __main__ import example_function', number=1000)
print(f"Execution time: {execution_time:.6f} seconds")
3. `memory_profiler`: `memory_profiler` 라이브러리는 파이썬 코드의 메모리 사용량을 측정할 수 있습니다. 데코레이터를 사용하여 특정 함수의 메모리 사용량을 확인할 수 있습니다.
먼저 `memory_profiler`를 설치해야 합니다.
pip install memory-profiler
예시코드:
from memory_profiler import profile
@profile
def example_function():
s = 0
for i in range(10000):
s += i
return s
def main():
example_function()
if __name__ == "__main__":
main()
위의 예시코드에서 `cProfile`은 `main()` 함수의 프로파일을 수행하고, `timeit`은 `example_function()`의 실행 시간을 측정합니다. `memory_profiler`는 `example_function()`의 메모리 사용량을 측정합니다. 이러한 프로파일링 도구를 사용하여 코드의 성능을 분석하고, 최적화할 수 있는 부분을 찾아 개선할 수 있습니다.
728x90