-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperformance_analyzer.py
More file actions
479 lines (406 loc) · 20 KB
/
Copy pathperformance_analyzer.py
File metadata and controls
479 lines (406 loc) · 20 KB
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
"""
Module 3: Performance Analyzer (v2)
Energy-Efficient CPU Scheduling — Benchmarker
----------------------------------------------
Fixes applied:
1. Tick-based timing (no wall clock)
2. Upgraded Baseline: Round Robin + Priority scheduling (not FIFO)
3. Cubic energy model (freq³) for both schedulers
4. Migration penalty reflected in stats
5. Deadline tracking + deadline_met% metric
Comparison: Energy-Efficient (DVFS+EDF+Thermal) vs Respectable Baseline (RR+Priority)
"""
import random
import tkinter as tk
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from collections import deque
from dataclasses import dataclass, field
from typing import List, Optional
from scheduling_core import (
EnergyEfficientScheduler,
Task, TaskPriority, TaskStatus,
CPUCore, CoreType,
ENERGY_COST_PER_UNIT, TICK_DURATION,
CONTEXT_SWITCH_COST_TICKS, NO_DEADLINE,
)
# ──────────────────────────────────────────
# FIX 2: Upgraded Baseline Scheduler
# Round Robin with Priority Queues — no DVFS, no thermal awareness
# ──────────────────────────────────────────
RR_QUANTUM = 2 # ticks per round-robin slot
class BaselineScheduler:
"""
Respectable baseline:
- Priority queues (HIGH / MEDIUM / LOW)
- Round Robin within each priority level
- Fixed frequency (no DVFS)
- No thermal awareness
- FIX 3: Cubic energy model (same formula, different freq)
- FIX 1: Tick-based clock
"""
def __init__(self):
self.cores = [
CPUCore(0, CoreType.P_CORE, max_frequency=3.6, min_frequency=1.2),
CPUCore(1, CoreType.P_CORE, max_frequency=3.6, min_frequency=1.2),
CPUCore(2, CoreType.E_CORE, max_frequency=2.0, min_frequency=0.8),
CPUCore(3, CoreType.E_CORE, max_frequency=2.0, min_frequency=0.8),
]
# FIX 2: three priority queues
self.queues = {
TaskPriority.HIGH: deque(),
TaskPriority.MEDIUM: deque(),
TaskPriority.LOW: deque(),
}
self.completed_tasks = []
self.missed_deadlines = []
self._task_counter = 0
self.tick = 0 # FIX 1: logical clock
# RR quantum tracking per core
self._rr_ticks = {c.core_id: 0 for c in self.cores}
def add_task(self, name, burst_time, priority, deadline_tick=NO_DEADLINE, load_profile=None):
self._task_counter += 1
if load_profile is None:
load_profile = {TaskPriority.HIGH: 0.9, TaskPriority.MEDIUM: 0.6, TaskPriority.LOW: 0.3}[priority]
t = Task(
task_id = self._task_counter,
name = name,
burst_time = burst_time,
priority = priority,
arrival_tick = self.tick, # FIX 1
deadline_tick = deadline_tick,
load_profile = load_profile,
)
self.queues[priority].append(t)
return t
def _next_task(self) -> Optional[Task]:
"""FIX 2: Pick from highest non-empty priority queue."""
for p in [TaskPriority.HIGH, TaskPriority.MEDIUM, TaskPriority.LOW]:
if self.queues[p]:
return self.queues[p].popleft()
return None
def step(self):
self.tick += 1
# FIX 5: check missed deadlines
for p in self.queues:
live = deque()
for t in self.queues[p]:
if t.deadline_tick != NO_DEADLINE and self.tick > t.deadline_tick:
t.status = TaskStatus.MISSED
t.finish_tick = self.tick
self.missed_deadlines.append(t)
else:
live.append(t)
self.queues[p] = live
# Fixed max freq (no DVFS) — runs hotter
for core in self.cores:
core.current_freq = core.max_frequency
core.current_load = (
random.uniform(0.5, 1.0) if not core.is_idle
else random.uniform(0.05, 0.15)
)
# Less efficient cooling (no thermal mgmt)
heat = core.current_load * core.current_freq * 8.0
cool = (core.temperature - 35.0) * 0.10
core.temperature = round(max(35.0, min(105.0, core.temperature + heat - cool)), 1)
# FIX 2: Round Robin preemption — return task to queue after quantum
for core in self.cores:
if not core.is_idle:
self._rr_ticks[core.core_id] += 1
if self._rr_ticks[core.core_id] >= RR_QUANTUM:
# preempt — put back in queue
task = core.current_task
core.current_task = None
self._rr_ticks[core.core_id] = 0
self.queues[task.priority].append(task)
# Assign tasks to free cores
for core in self.cores:
if core.is_idle:
task = self._next_task()
if task:
core.current_task = task
task.assigned_core = core.core_id
task.status = TaskStatus.RUNNING
if task.start_tick is None:
task.start_tick = self.tick # FIX 1
# Progress tasks
for core in self.cores:
if core.is_idle:
# Baseline still burns idle leakage power continuously
base_p = 0.5 if core.core_type == CoreType.P_CORE else 0.2
energy = base_p * TICK_DURATION * ENERGY_COST_PER_UNIT
core.total_energy += energy
core.idle_energy += energy
continue
task = core.current_task
# Baseline energy: base_power + dynamic_power
base_p = 0.5 if core.core_type == CoreType.P_CORE else 0.2
dyn_p = (core.current_freq**3) * core.current_load
energy = (base_p + dyn_p) * TICK_DURATION * ENERGY_COST_PER_UNIT
core.total_energy += energy
task.energy_used += energy
# DVFS performance impact
progress_speed = core.current_freq / core.max_frequency
task.burst_time -= TICK_DURATION * progress_speed
if task.burst_time <= 0:
task.status = TaskStatus.COMPLETED
task.finish_tick = self.tick # FIX 1
self.completed_tasks.append(task)
core.current_task = None
self._rr_ticks[core.core_id] = 0
def run(self, ticks):
for _ in range(ticks):
self.step()
def get_stats(self):
done = self.completed_tasks
if not done:
return {}
n = len(done)
te = sum(t.energy_used for t in done)
awt = sum(t.waiting_time for t in done) / n
att = sum(t.turnaround_time for t in done) / n
normalized_tats = [t.normalized_turnaround_time for t in done if t.original_burst > 0]
fi = (sum(normalized_tats)**2) / (len(normalized_tats) * sum(x**2 for x in normalized_tats)) if normalized_tats else 0
dl_met = sum(1 for t in done if t.deadline_met)
peak_t = max(c.temperature for c in self.cores)
return {
"total_tasks_completed": n,
"missed_deadlines": len(self.missed_deadlines),
"deadline_met_pct": round(dl_met / max(n, 1) * 100, 1),
"total_energy_joules": round(te, 4),
"idle_leakage_joules": round(sum(c.idle_energy for c in self.cores), 4),
"avg_waiting_time_s": round(awt, 3),
"avg_turnaround_time_s": round(att, 3),
"fairness_index": round(fi, 4),
"peak_temperature_c": round(peak_t, 1),
"total_migration_penalty": 0,
}
# ──────────────────────────────────────────
# Benchmark Task Set (with deadlines — FIX 5)
# ──────────────────────────────────────────
TASK_SET = [
("Video Encode", 2.5, TaskPriority.HIGH, 25),
("Background Sync", 1.5, TaskPriority.LOW, NO_DEADLINE),
("UI Render", 1.0, TaskPriority.MEDIUM, 15),
("DB Backup", 3.0, TaskPriority.LOW, NO_DEADLINE),
("Network Poll", 0.5, TaskPriority.MEDIUM, 10),
("ML Inference", 3.5, TaskPriority.HIGH, 30),
("Log Rotate", 1.0, TaskPriority.LOW, NO_DEADLINE),
("Cache Warm", 2.0, TaskPriority.MEDIUM, 25),
("Auth Token", 0.5, TaskPriority.HIGH, 8),
("Image Resize", 2.5, TaskPriority.LOW, NO_DEADLINE),
]
TICKS = 30
def run_benchmark():
# ── Energy-Efficient
eff = EnergyEfficientScheduler()
for name, burst, priority, dl in TASK_SET:
eff.add_task(name, burst, priority, deadline_tick=dl)
eff_energy = []
eff_temp = []
eff_freq = []
eff_completed_over_time = []
for _ in range(TICKS):
eff.step()
eff_energy.append(sum(c.total_energy for c in eff.cores))
eff_temp.append(max(c.temperature for c in eff.cores))
eff_freq.append(sum(c.current_freq for c in eff.cores) / len(eff.cores))
eff_completed_over_time.append(len(eff.completed_tasks))
eff_stats = eff.get_stats()
eff_stats["peak_temperature_c"] = round(max(eff_temp), 1)
# ── Baseline (RR + Priority)
base = BaselineScheduler()
for name, burst, priority, dl in TASK_SET:
base.add_task(name, burst, priority, deadline_tick=dl)
base_energy = []
base_temp = []
base_freq = []
base_completed_over_time = []
for _ in range(TICKS):
base.step()
base_energy.append(sum(c.total_energy for c in base.cores))
base_temp.append(max(c.temperature for c in base.cores))
base_freq.append(sum(c.current_freq for c in base.cores) / len(base.cores))
base_completed_over_time.append(len(base.completed_tasks))
base_stats = base.get_stats()
base_stats["peak_temperature_c"] = round(max(base_temp), 1)
return dict(
eff_stats=eff_stats, base_stats=base_stats,
eff_energy=eff_energy, base_energy=base_energy,
eff_temp=eff_temp, base_temp=base_temp,
eff_freq=eff_freq, base_freq=base_freq,
eff_completed=eff_completed_over_time,
base_completed=base_completed_over_time,
ticks=TICKS,
)
# ──────────────────────────────────────────
# Theme + UI
# ──────────────────────────────────────────
THEME = {
"bg": "#0a0e14", "panel": "#111820", "border": "#1e2d3d",
"text": "#cdd9e5", "dim": "#4d6a7a",
"eff": "#39c5cf", "base": "#e05252",
"accent": "#f0a500", "green": "#4ec94e",
}
class AnalyzerWindow:
def __init__(self, root):
self.root = root
self.root.title("Performance Analyzer v2 — EfficientScheduler vs RR+Priority Baseline")
self.root.configure(bg=THEME["bg"])
self.root.geometry("1300x840")
self._build_header()
self._build_loading()
self.root.after(200, self._run_and_render)
def _build_header(self):
h = tk.Frame(self.root, bg=THEME["bg"], pady=10)
h.pack(fill="x", padx=20)
tk.Label(h, text="📊 PERFORMANCE ANALYZER",
bg=THEME["bg"], fg=THEME["eff"],
font=("Courier New", 16, "bold")).pack(side="left")
tk.Label(h, text="Energy-Efficient (DVFS+EDF) vs RR+Priority Baseline",
bg=THEME["bg"], fg=THEME["dim"],
font=("Courier New", 10)).pack(side="left", padx=16)
def _build_loading(self):
self.loading = tk.Label(self.root, text="Running benchmark...",
bg=THEME["bg"], fg=THEME["dim"],
font=("Courier New", 12))
self.loading.pack(expand=True)
def _run_and_render(self):
r = run_benchmark()
self.loading.destroy()
self._build_ui(r)
def _build_ui(self, r):
content = tk.Frame(self.root, bg=THEME["bg"])
content.pack(fill="both", expand=True, padx=20, pady=(0, 14))
left = tk.Frame(content, bg=THEME["bg"])
left.pack(side="left", fill="both", expand=True)
right = tk.Frame(content, bg=THEME["bg"], width=320)
right.pack(side="right", fill="y", padx=(14, 0))
right.pack_propagate(False)
self._build_charts(left, r)
self._build_stats(right, r)
def _build_charts(self, parent, r):
fig = plt.Figure(figsize=(8.5, 6.5), facecolor=THEME["bg"])
gs = gridspec.GridSpec(2, 2, figure=fig, hspace=0.5, wspace=0.35)
x = list(range(r["ticks"]))
# Energy
ax1 = fig.add_subplot(gs[0, 0])
self._style(ax1, "CUMULATIVE ENERGY (J)")
ax1.plot(x, r["eff_energy"], color=THEME["eff"], lw=2, label="Efficient")
ax1.plot(x, r["base_energy"], color=THEME["base"], lw=2, label="Baseline")
ax1.fill_between(x, r["eff_energy"], r["base_energy"], alpha=0.08, color=THEME["eff"])
ax1.legend(facecolor=THEME["panel"], edgecolor=THEME["border"],
labelcolor=THEME["text"], fontsize=8)
# Completed Tasks
ax_comp = fig.add_subplot(gs[0, 1])
self._style(ax_comp, "COMPLETED TASKS")
ax_comp.plot(x, r["eff_completed"], color=THEME["eff"], lw=2, label="Efficient", drawstyle='steps-post')
ax_comp.plot(x, r["base_completed"], color=THEME["base"], lw=2, label="Baseline", drawstyle='steps-post')
ax_comp.legend(facecolor=THEME["panel"], edgecolor=THEME["border"], labelcolor=THEME["text"], fontsize=8)
# Temperature
ax2 = fig.add_subplot(gs[1, 0])
self._style(ax2, "PEAK TEMPERATURE (°C)", ylim=(30, 110))
ax2.plot(x, r["eff_temp"], color=THEME["eff"], lw=1.8, label="Efficient")
ax2.plot(x, r["base_temp"], color=THEME["base"], lw=1.8, label="Baseline")
ax2.axhline(85, color=THEME["accent"], lw=0.8, linestyle="--", alpha=0.5)
ax2.axhline(95, color=THEME["base"], lw=0.8, linestyle="--", alpha=0.5)
ax2.legend(facecolor=THEME["panel"], edgecolor=THEME["border"],
labelcolor=THEME["text"], fontsize=7)
# Frequency
ax3 = fig.add_subplot(gs[1, 1])
self._style(ax3, "AVG FREQUENCY (GHz)", ylim=(0, 4.0))
ax3.plot(x, r["eff_freq"], color=THEME["eff"], lw=1.8, label="Efficient")
ax3.plot(x, r["base_freq"], color=THEME["base"], lw=1.8, label="Baseline")
ax3.legend(facecolor=THEME["panel"], edgecolor=THEME["border"],
labelcolor=THEME["text"], fontsize=7)
canvas = FigureCanvasTkAgg(fig, master=parent)
canvas.get_tk_widget().pack(fill="both", expand=True)
canvas.draw()
def _style(self, ax, title, ylim=None):
ax.set_facecolor(THEME["panel"])
ax.tick_params(colors=THEME["dim"], labelsize=7)
ax.set_title(title, color=THEME["dim"], fontsize=8,
fontfamily="monospace", loc="left", pad=4)
if ylim:
ax.set_ylim(*ylim)
for spine in ax.spines.values():
spine.set_edgecolor(THEME["border"])
ax.grid(color=THEME["border"], linewidth=0.4, linestyle="--", alpha=0.5)
def _build_stats(self, parent, r):
es, bs = r["eff_stats"], r["base_stats"]
tk.Label(parent, text="BENCHMARK RESULTS",
bg=THEME["bg"], fg=THEME["dim"],
font=("Courier New", 9, "bold")).pack(anchor="w", pady=(4, 8))
# label, key, unit, lower_is_better
metrics = [
("Tasks Completed", "total_tasks_completed", "", False),
("Missed Deadlines", "missed_deadlines", "", True),
("Deadline Met %", "deadline_met_pct", "%", False),
("Total Energy (J)", "total_energy_joules", "J", True),
("Idle Leakage (J)", "idle_leakage_joules", "J", True),
("Migration Cost", "total_migration_penalty","", True),
("Avg Wait (s)", "avg_waiting_time_s", "s", True),
("Avg Turnaround (s)", "avg_turnaround_time_s", "s", True),
("Peak Temp (°C)", "peak_temperature_c", "°C", True),
("Fairness Index", "fairness_index", "", False),
]
for label, key, unit, lower_better in metrics:
ev = es.get(key, "N/A")
bv = bs.get(key, "N/A")
try:
if lower_better:
ec = THEME["green"] if float(ev) <= float(bv) else THEME["base"]
bc = THEME["green"] if float(bv) <= float(ev) else THEME["base"]
else:
ec = THEME["green"] if float(ev) >= float(bv) else THEME["base"]
bc = THEME["green"] if float(bv) >= float(ev) else THEME["base"]
except (TypeError, ValueError):
ec = bc = THEME["text"]
card = tk.Frame(parent, bg=THEME["panel"],
highlightbackground=THEME["border"], highlightthickness=1)
card.pack(fill="x", pady=2)
tk.Label(card, text=label, bg=THEME["panel"],
fg=THEME["dim"], font=("Courier New", 7)).pack(anchor="w", padx=8, pady=(5, 1))
row = tk.Frame(card, bg=THEME["panel"])
row.pack(fill="x", padx=8, pady=(0, 5))
ef = tk.Frame(row, bg=THEME["panel"])
ef.pack(side="left", expand=True)
tk.Label(ef, text="EFFICIENT", bg=THEME["panel"],
fg=THEME["eff"], font=("Courier New", 6)).pack()
tk.Label(ef, text=f"{ev}{unit}", bg=THEME["panel"],
fg=ec, font=("Courier New", 10, "bold")).pack()
tk.Label(row, text="vs", bg=THEME["panel"],
fg=THEME["dim"], font=("Courier New", 7)).pack(side="left", padx=4)
bf = tk.Frame(row, bg=THEME["panel"])
bf.pack(side="left", expand=True)
tk.Label(bf, text="RR+PRIORITY", bg=THEME["panel"],
fg=THEME["base"], font=("Courier New", 6)).pack()
tk.Label(bf, text=f"{bv}{unit}", bg=THEME["panel"],
fg=bc, font=("Courier New", 10, "bold")).pack()
# Summary box
try:
e_saved = round((1 - float(es["total_energy_joules"]) / float(bs["total_energy_joules"])) * 100, 1)
t_saved = round(float(bs["peak_temperature_c"]) - float(es["peak_temperature_c"]), 1)
dl_diff = int(bs.get("missed_deadlines", 0)) - int(es.get("missed_deadlines", 0))
col = THEME["green"] if e_saved > 0 else THEME["base"]
summary = tk.Frame(parent, bg=THEME["panel"],
highlightbackground=THEME["eff"], highlightthickness=1)
summary.pack(fill="x", pady=(10, 0))
tk.Label(summary, text="EFFICIENCY GAINS", bg=THEME["panel"],
fg=THEME["eff"], font=("Courier New", 8, "bold")).pack(anchor="w", padx=8, pady=(6, 2))
tk.Label(
summary,
text=f" ⚡ Energy saved: {e_saved}%\n"
f" 🌡 Temp reduced: {t_saved}°C\n"
f" ⏰ Fewer misses: {dl_diff} tasks\n"
f" ✓ Fairness: {es.get('fairness_index','N/A')}",
bg=THEME["panel"], fg=col,
font=("Courier New", 9), justify="left"
).pack(anchor="w", padx=8, pady=(0, 8))
except Exception:
pass
if __name__ == "__main__":
root = tk.Tk()
app = AnalyzerWindow(root)
root.mainloop()