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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
| import psutil
import time
import threading
import matplotlib.pyplot as plt
from collections import deque
import tkinter as tk
from tkinter import ttk
import queue
class RealTimeMemoryMonitor:
def __init__(self, max_points=100):
self.max_points = max_points
self.memory_data = deque(maxlen=max_points)
self.time_data = deque(maxlen=max_points)
self.cpu_data = deque(maxlen=max_points)
self.running = False
self.process = psutil.Process()
def get_system_info(self):
"""시스템 정보 수집"""
memory = psutil.virtual_memory()
cpu_percent = psutil.cpu_percent(interval=0.1)
process_memory = self.process.memory_info().rss / 1024 / 1024 # MB
return {
'total_memory': memory.total / 1024 / 1024 / 1024, # GB
'used_memory': memory.used / 1024 / 1024 / 1024, # GB
'memory_percent': memory.percent,
'cpu_percent': cpu_percent,
'process_memory': process_memory
}
def start_monitoring(self, interval=1.0):
"""모니터링 시작"""
self.running = True
def monitor_loop():
start_time = time.time()
while self.running:
current_time = time.time() - start_time
system_info = self.get_system_info()
self.time_data.append(current_time)
self.memory_data.append(system_info['memory_percent'])
self.cpu_data.append(system_info['cpu_percent'])
time.sleep(interval)
self.monitor_thread = threading.Thread(target=monitor_loop)
self.monitor_thread.daemon = True
self.monitor_thread.start()
def stop_monitoring(self):
"""모니터링 중지"""
self.running = False
if hasattr(self, 'monitor_thread'):
self.monitor_thread.join()
def plot_data(self):
"""데이터 시각화"""
if not self.time_data:
return
plt.figure(figsize=(12, 8))
# 메모리 사용률 그래프
plt.subplot(2, 1, 1)
plt.plot(list(self.time_data), list(self.memory_data), 'b-', label='Memory %')
plt.ylabel('Memory Usage (%)')
plt.title('Real-time System Monitor')
plt.legend()
plt.grid(True)
# CPU 사용률 그래프
plt.subplot(2, 1, 2)
plt.plot(list(self.time_data), list(self.cpu_data), 'r-', label='CPU %')
plt.xlabel('Time (seconds)')
plt.ylabel('CPU Usage (%)')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
class MemoryMonitorGUI:
def __init__(self):
self.monitor = RealTimeMemoryMonitor()
self.root = tk.Tk()
self.root.title("실시간 메모리 모니터")
self.root.geometry("400x300")
self.create_widgets()
self.update_data()
def create_widgets(self):
# 메인 프레임
main_frame = ttk.Frame(self.root, padding="10")
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# 시스템 정보 표시
self.info_frame = ttk.LabelFrame(main_frame, text="시스템 정보", padding="5")
self.info_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
self.memory_label = ttk.Label(self.info_frame, text="메모리: ")
self.memory_label.grid(row=0, column=0, sticky=tk.W)
self.cpu_label = ttk.Label(self.info_frame, text="CPU: ")
self.cpu_label.grid(row=1, column=0, sticky=tk.W)
self.process_label = ttk.Label(self.info_frame, text="프로세스 메모리: ")
self.process_label.grid(row=2, column=0, sticky=tk.W)
# 제어 버튼
self.start_button = ttk.Button(main_frame, text="모니터링 시작",
command=self.start_monitoring)
self.start_button.grid(row=1, column=0, pady=10)
self.stop_button = ttk.Button(main_frame, text="모니터링 중지",
command=self.stop_monitoring)
self.stop_button.grid(row=1, column=1, pady=10)
self.plot_button = ttk.Button(main_frame, text="그래프 보기",
command=self.show_plot)
self.plot_button.grid(row=2, column=0, columnspan=2, pady=10)
def start_monitoring(self):
"""모니터링 시작"""
self.monitor.start_monitoring()
self.start_button.config(state='disabled')
self.stop_button.config(state='normal')
def stop_monitoring(self):
"""모니터링 중지"""
self.monitor.stop_monitoring()
self.start_button.config(state='normal')
self.stop_button.config(state='disabled')
def show_plot(self):
"""그래프 표시"""
self.monitor.plot_data()
def update_data(self):
"""데이터 업데이트"""
try:
system_info = self.monitor.get_system_info()
self.memory_label.config(
text=f"메모리: {system_info['memory_percent']:.1f}% "
f"({system_info['used_memory']:.1f}/{system_info['total_memory']:.1f} GB)"
)
self.cpu_label.config(text=f"CPU: {system_info['cpu_percent']:.1f}%")
self.process_label.config(
text=f"프로세스 메모리: {system_info['process_memory']:.1f} MB"
)
except Exception as e:
print(f"데이터 업데이트 오류: {e}")
# 1초마다 업데이트
self.root.after(1000, self.update_data)
def run(self):
"""GUI 실행"""
self.root.mainloop()
# 사용 예제
if __name__ == "__main__":
# 콘솔 모드
print("실시간 메모리 모니터 (콘솔 모드)")
monitor = RealTimeMemoryMonitor()
monitor.start_monitoring()
try:
time.sleep(10) # 10초 동안 모니터링
monitor.plot_data()
except KeyboardInterrupt:
pass
finally:
monitor.stop_monitoring()
# GUI 모드 (주석 해제하여 사용)
# gui = MemoryMonitorGUI()
# gui.run()
|