Python/Analysis to Python
[change type of whole list] : 속도 비교(performance testing )
샰롯
2022. 5. 24. 18:56
[change type of whole list] : performance testing
→ comparison for loops and list comprehension and map
→ for문과 리스트 컨프리헨션, 맵의 속도 비교
시작에 앞서
이 글은 list안 요소의 type 변환 시 map()을 사용하는 것을 추천합니다.
*결과값 읽는 법
→ %%timeit
%%timeit -n 10
코드를 반복 하여 평균 실행 속도를 구하는 코드
-n [num_loop] : [num_loop]에 반복 실행할 숫자를 입력(위 코드는 10번을 돌리라는 의미)
→ %%timeit 결과값 읽는 법
959 ms ± 8.6 ms per loop (mean ± std. dev. of 7 runs, 10 loop each)
10번 반복하여 얻은 평균 실행 속도(959 ms ± 8.6 ms)
change type of whole list
- 공백이 포함된 Str type → Int type in List로 변환
→ 공백이 포함된 문자열 바인딩
test_str = '1 2 3 4 5 6 7 8 9 0 '*1_000_000
TMI : Python 3.6에 추가된 문법으로 _를 사용하여 자릿수 구분이 가능
→ for문
%%timeit -n 10
test_list = []
for i in test_str.split():
test_list.append(int(i))
959 ms ± 7.18 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
→ list comprehension
%%timeit -n 10
test_list = [int(i) for i in test_str.split()]
824 ms ± 6.31 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
→ map()
%%timeit -n 10
test_list = list(map(int, test_str.split()))
600 ms ± 6.27 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
결과 분석
- for 문
959 ms ± 7.18 ms per loop - list comprehension
824 ms ± 6.31 ms per loop - map()
600 ms ± 6.27 ms per loop
리스트 안의 요소 type을 바꾸는 방법은 map()이 빠르다는 것을 알 수 있다.
list comprehension을 사용한 type변경
- 다차원 리스트 구조의 경우 간결하게 구현이 가능하다.
→ 다차원 문자열 리스트 바인딩
str_list = [['1', '2'], ['3', '4']]
→ Str type in List → Int type in List로 변환
int_list = [[int(i) for i in sublist] for sublist in str_list]
int_list
[[1, 2], [3, 4]]
→ 실행 속도 확인
%%timeit
int_list = [[int(i) for i in sublist] for sublist in str_list]
567 ns ± 4.58 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
내용 정리
- 코딩 실행속도를 0.1~0.2초 빠르게 해야 할 경우 : map() 사용을 추천한다.
Ex.코딩 테스트 및 백준, 등 - 본 내용에서 비교한 방법은 구현에 따라 차이가 있을 수 있다.