1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
| import array
import collections
import sys
from collections import defaultdict, Counter
class DataStructureOptimization:
"""데이터 구조 최적화 예제"""
def list_vs_array_comparison(self):
"""리스트 vs 배열 메모리 사용량 비교"""
# 일반 리스트
normal_list = [i for i in range(10000)]
# array 모듈 사용
int_array = array.array('i', range(10000))
print("=== 메모리 사용량 비교 ===")
print(f"일반 리스트: {sys.getsizeof(normal_list)} bytes")
print(f"array.array: {sys.getsizeof(int_array)} bytes")
print(f"메모리 절약: {sys.getsizeof(normal_list) / sys.getsizeof(int_array):.2f}배")
def collections_optimization(self):
"""collections 모듈 최적화"""
# defaultdict 사용
def count_words_dict(words):
"""일반 딕셔너리로 단어 개수 세기"""
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
def count_words_defaultdict(words):
"""defaultdict로 단어 개수 세기"""
word_count = defaultdict(int)
for word in words:
word_count[word] += 1
return dict(word_count)
def count_words_counter(words):
"""Counter로 단어 개수 세기"""
return dict(Counter(words))
# 테스트 데이터
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'] * 1000
benchmark = PerformanceBenchmark()
print("\n=== 단어 개수 세기 성능 비교 ===")
benchmark.compare_functions(
[count_words_dict, count_words_defaultdict, count_words_counter],
words
)
def string_optimization(self):
"""문자열 처리 최적화"""
def string_concat_plus(strings):
"""+ 연산자로 문자열 연결"""
result = ""
for s in strings:
result += s
return result
def string_concat_join(strings):
"""join으로 문자열 연결"""
return "".join(strings)
def string_concat_format(strings):
"""format으로 문자열 연결"""
return "{}".format("".join(strings))
# 테스트 데이터
test_strings = ["hello"] * 1000
benchmark = PerformanceBenchmark()
print("\n=== 문자열 연결 성능 비교 ===")
benchmark.compare_functions(
[string_concat_plus, string_concat_join, string_concat_format],
test_strings
)
# __slots__ 최적화 예제
class RegularClass:
"""일반 클래스"""
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class OptimizedClass:
"""__slots__를 사용한 최적화된 클래스"""
__slots__ = ['x', 'y', 'z']
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def slots_optimization_demo():
"""__slots__ 최적화 데모"""
import sys
# 객체 생성
regular_obj = RegularClass(1, 2, 3)
optimized_obj = OptimizedClass(1, 2, 3)
print("=== __slots__ 메모리 최적화 ===")
print(f"일반 클래스 객체: {sys.getsizeof(regular_obj.__dict__)} bytes")
print(f"__slots__ 클래스 객체: {sys.getsizeof(optimized_obj)} bytes")
# 많은 객체 생성 시 메모리 사용량 비교
regular_objects = [RegularClass(i, i+1, i+2) for i in range(10000)]
optimized_objects = [OptimizedClass(i, i+1, i+2) for i in range(10000)]
regular_total = sum(sys.getsizeof(obj.__dict__) for obj in regular_objects)
optimized_total = sum(sys.getsizeof(obj) for obj in optimized_objects)
print(f"\n10,000개 객체 메모리 사용량:")
print(f"일반 클래스: {regular_total:,} bytes")
print(f"__slots__ 클래스: {optimized_total:,} bytes")
print(f"메모리 절약: {regular_total / optimized_total:.2f}배")
if __name__ == "__main__":
optimizer = DataStructureOptimization()
optimizer.list_vs_array_comparison()
optimizer.collections_optimization()
optimizer.string_optimization()
slots_optimization_demo()
|