8000 FrontEnd 4.5/2: Finished · JayAyAre/PyScript-vs-JavaScript@cd2d295 · GitHub
[go: up one dir, main page]

Skip to content

Commit cd2d295

Browse files
committed
FrontEnd 4.5/2: Finished
1 parent 5569dcf commit cd2d295

File tree

14 files changed

+95
-105
lines changed

14 files changed

+95
-105
lines changed

Astro-TFG/public/scripts/4.5-criptografia/prueba-1/version-1/javascript/main.js

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -80,29 +80,10 @@ function initializeWorker() {
8080

8181
worker = new Worker(workerPath);
8282

83-
worker.onmessage = (event) => {
84-
const { id, results, error, metrics } = event.data;
85-
86-
if (error && pendingPromises.has(id)) {
87-
pendingPromises.get(id).reject(error);
88-
pendingPromises.delete(id);
89-
return;
90-
}
91-
92-
if (pendingPromises.has(id)) {
93-
pendingPromises.get(id).resolve({
94-
results,
95-
metrics
96-
});
97-
pendingPromises.delete(id);
98-
}
99-
};
100-
10183
resolve();
10284
});
10385
}
10486

105-
// dejar expuesta
10687
window.runJSBenchmark = javascriptBenchmark;
10788

10889

Original file line numberDiff line numberDiff line change
@@ -1,54 +1,45 @@
11
// main.js
22
let worker = null;
3-
let jsTimer = null;
4-
let jsStartTime = 0;
53

6-
function startJsTimer() {
7-
jsStartTime = performance.now();
8-
const timerElement = document.getElementById("js-timer-display");
9-
function updateTimer() {
10-
if (!jsTimer) return;
11-
const elapsed = ((performance.now() - jsStartTime) / 1000).toFixed(3);
12-
timerElement.textContent = `JS Timer: ${elapsed} s`;
13-
jsTimer = requestAnimationFrame(updateTimer);
14-
}
15-
cancelAnimationFrame(jsTimer);
16-
jsTimer = requestAnimationFrame(updateTimer);
17-
}
4+
function displayResult(r, workerTime) {
5+
const out = document.getElementById("javascript-output");
186

19-
function stopJsTimer() {
20-
cancelAnimationFrame(jsTimer);
21-
jsTimer = null;
22-
const elapsed = ((performance.now() - jsStartTime) / 1000).toFixed(3);
23-
document.getElementById(
24-
"js-timer-display"
25-
).textContent = `JS Timer: ${elapsed} s`;
7+
out.innerHTML = `
8+
<div>Worker init time: ${workerTime.toFixed(2)} ms</div>
9+
<div>Message size: ${r.message_size_mb.toFixed(2)} MB</div>
10+
<div>Repetitions: ${r.repetitions}</div>
11+
<div>Avg encrypt time: ${r.encrypt_avg_ms.toFixed(2)} ms</div>
12+
<div>Avg decrypt time: ${r.decrypt_avg_ms.toFixed(2)} ms</div>
13+
<div>Integrity check: ${r.integrity_ok ? "OK" : "FAIL"}</div>
14+
<div>Integrity success: ${r.success_count} of ${r.repetitions
15+
} (${r.success_percentage.toFixed(2)}%)</div>
16+
<div>Ciphertext size: ${(r.ciphertext_bytes / 1024 / 1024).toFixed(
17+
2
18+
)} MB</div>
19+
<div>Total crypto time: ${r.crypto_total_ms.toFixed(2)} ms</div>
20+
<div>Overall total time: ${r.overall_time_ms.toFixed(2)} ms</div>
21+
`;
2622
}
2723

2824
async function javascriptBenchmark() {
2925
try {
30-
startJsTimer();
3126

32-
// measure Worker init time
27+
window.clearCell("javascript-output");
28+
window.showExecutionLoader();
29+
3330
const startWorkerTime = performance.now();
34-
if (!worker) {
35-
worker = new Worker("./javascript/worker.js");
36-
}
31+
await initializeWorker();
3732
const workerTime = performance.now() - startWorkerTime;
3833

39-
clearCell("javascript");
40-
41-
// read inputs
4234
const repetitions = parseInt(
43-
document.getElementById("num-repetitions-js").value,
35+
document.getElementById("num-repetitions-javascript").value,
4436
10
4537
);
4638
const messageSizeMb = parseFloat(
47-
document.getElementById("message-size-js").value
39+
document.getElementById("message-size-javascript").value
4840
);
4941
const id = `js-${Date.now()}`;
5042

51-
// dispatch to worker
5243
const resultJson = await new Promise((resolve, reject) => {
5344
function onMessage(e) {
5445
if (e.data.id !== id) return;
@@ -73,44 +64,28 @@ async function javascriptBenchmark() {
7364
displayResult(result, workerTime);
7465
} catch (err) {
7566
console.error("Benchmark error:", err);
76-
document.getElementById(
77-
"javascript-output"
78-
).textContent = `Error: ${err.message}`;
67+
const out = document.getElementById("javascript-output");
68+
out.textContent = `Error: ${err.message}`;
7969
} finally {
80-
stopJsTimer();
70+
window.hideExecutionLoader();
8171
}
8272
}
8373

84-
function clearCell(prefix) {
85-
["output", "exact"].forEach((field) => {
86-
const el = document.getElementById(`${prefix}-${field}`);
87-
if (el) el.textContent = "";
88-
});
89-
}
74+
function initializeWorker() {
75+
return new Promise((resolve) => {
76+
if (worker) {
77+
resolve();
78+
return;
79+
}
9080

91-
function displayResult(r, workerTime) {
92-
const out = document.getElementById("javascript-output");
93-
const exact = document.getElementById("javascript-exact");
81+
const workerPath = window.location.origin +
82+
window.document.body.dataset.jsPath +
83+
"worker.js";
9484

95-
out.innerHTML = `
96-
<div>Worker init time: ${workerTime.toFixed(2)} ms</div>
97-
<div>Message size: ${r.message_size_mb.toFixed(2)} MB</div>
98-
<div>Repetitions: ${r.repetitions}</div>
99-
<div>Avg encrypt time: ${r.encrypt_avg_ms.toFixed(2)} ms</div>
100-
<div>Avg decrypt time: ${r.decrypt_avg_ms.toFixed(2)} ms</div>
101-
<div>Integrity check: ${r.integrity_ok ? "OK" : "FAIL"}</div>
102-
<div>Integrity success: ${r.success_count} of ${
103-
r.repetitions
104-
} (${r.success_percentage.toFixed(2)}%)</div>
105-
<div>Ciphertext size: ${(r.ciphertext_bytes / 1024 / 1024).toFixed(
106-
2
107-
)} MB</div>
108-
`;
109-
exact.innerHTML = `
110-
F438 <div>Total crypto time: ${r.crypto_total_ms.toFixed(2)} ms</div>
111-
<div>Overall total time: ${r.overall_time_ms.toFixed(2)} ms</div>
112-
`;
85+
worker = new Worker(workerPath);
86+
resolve();
87+
});
11388
}
11489

115-
// expose globally
116-
window.javascriptBenchmark = javascriptBenchmark;
90+
window.runJSBenchmark = javascriptBenchmark;
91+

Astro-TFG/public/scripts/4.5-criptografia/prueba-2/javascript/worker.js renamed to Astro-TFG/public/scripts/4.5-criptografia/prueba-2/version-1/javascript/worker.js

Lines changed: 2 additions & 2 deletions
10000
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ self.addEventListener("message", async (event) => {
55

66
const { id, repetitions, messageSizeMb } = data;
77
try {
8-
// small delay to mimic async setup
98
await new Promise((r) => setTimeout(r, 100));
109

1110
const fileSizeBytes = Math.floor(messageSizeMb * 1024 * 1024);
@@ -19,6 +18,7 @@ self.addEventListener("message", async (event) => {
1918
const t0 = performance.now();
2019

2120
for (let i = 0; i < repetitions; i++) {
21+
2222
// generate AES-GCM key
2323
const key = await crypto.subtle.generateKey(
2424
{ name: "AES-GCM", length: 128 },
@@ -49,7 +49,7 @@ self.addEventListener("message", async (event) => {
4949
successCount++;
5050
}
5151
} catch (_) {
52-
// fail silently
52+
console.error("Decryption failed");
5353
}
5454
totalDec += performance.now() - decStart;
5555
}
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"files": {
3-
"/python/worker.py": "worker.py"
3+
"../python/worker.py": "worker.py"
44
},
55
"packages": ["pycryptodome"]
6-
}
6+
}

Astro-TFG/public/scripts/4.5-criptografia/prueba-2/python/main.py renamed to Astro-TFG/public/scripts/4.5-criptografia/prueba-2/version-1/python/main.py

Lines changed: 41 additions & 11 deletions
77
Original file line numberDiff line numberDiff line change
@@ -9,25 +9,47 @@
99

1010
async def launch_worker(event):
1111
global worker
12-
js.clearCell("pyscript")
13-
js.startPyTimer()
14-
start_w = time.perf_counter()
12+
start_worker_time = time.perf_counter()
1513

1614
if worker is None:
15+
base = js.window.location.origin + js.window.document.body.dataset.pyPath
1716
worker = PyWorker(
18-
"./python/worker.py",
17+
f"{base}worker.py",
1918
type="pyodide",
20-
config="./json/pyscript-worker.json"
19+
config=f"{base.replace('python', 'json')}pyscript-worker.json"
2120
)
2221
await worker.ready
2322

24-
worker_time = (time.perf_counter() - start_w) * 1000
25-
# Llamada al worker; devuelve JSON serializado
26-
result_json = await worker.sync.js_run_py_benchmark(worker_time)
23+
worker_time = (time.perf_counter() - start_worker_time) * 1000
24+
25+
result_json = await worker.sync.do_hash(worker_time)
2726
result = json.loads(result_json)
2827

2928
display_result(result, worker_time)
30-
js.stopPyTimer()
29+
30+
31+
async def launch_worker(event):
32+
try:
33+
global worker
34+
start_worker_time = time.perf_counter()
35+
36+
if worker is None:
37+
base = js.window.location.origin + js.window.document.body.dataset.pyPath
38+
worker = PyWorker(
39+
f"{base}worker.py",
40+
type="pyodide",
41+
config=f"{base.replace('python', 'json')}pyscript-worker.json"
42+
)
43+
await worker.ready
44+
45+
worker_time = (time.perf_counter() - start_worker_time) * 1000
46+
json_str = await worker.sync.do_hash(worker_time)
47+
result = json.loads(json_str)
48+
49+
display_result(result, worker_time)
50+
js.window.hideExecutionLoader()
51+
except Exception as e:
52+
display(f"Error: {e}", target="pyscript-output")
3153

3254

3355
def display_result(r, worker_time):
@@ -49,6 +71,14 @@ def display_result(r, worker_time):
4971
f"Ciphertext size: {(r['ciphertext_bytes']/1024**2):.2f} MB", target="pyscript-output")
5072

5173
display(
52-
f"Total crypto time: {r['crypto_total_ms']:.2f} ms", target="pyscript-exact")
74+
f"Total crypto time: {r['crypto_total_ms']:.2f} ms", target="pyscript-output")
5375
display(
54-
f"Overall total time: {r['overall_time_ms']:.2f} ms", target="pyscript-exact")
76+
f"Overall total time: {r['overall_time_ms']:.2f} ms", target="pyscript-output")
+
78+
79+
def js_run_py_benchmark(event):
80+
js.clearCell('pyscript-output')
81+
asyncio.ensure_future(launch_worker(None))
82+
83+
84+
js.window.run_py_benchmark = js_run_py_benchmark

Astro-TFG/public/scripts/4.5-criptografia/prueba-2/python/worker.py renamed to Astro-TFG/public/scripts/4.5-criptografia/prueba-2/version-1/python/worker.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@
77
from Crypto.Random import get_random_bytes
88

99

10-
async def js_run_py_benchmark(worker_time):
10+
async def do_hash(worker_time):
1111
await asyncio.sleep(0.1)
1212

13-
reps = int(document.getElementById("num-repetitions-py").value)
14-
size_mb = float(document.getElementById("message-size-py").value)
13+
reps = int(document.getElementById("num-repetitions-pyscript").value)
14+
size_mb = float(document.getElementById("message-size-pyscript").value)
1515
size_b = int(size_mb * 1024 * 1024)
1616

1717
plaintext = os.urandom(size_b)
@@ -58,4 +58,4 @@ async def js_run_py_benchmark(worker_time):
5858
}
5959
return json.dumps(result)
6060

61-
sync.js_run_py_benchmark = js_run_py_benchmark
61+
sync.do_hash = do_hash

Astro-TFG/src/data/tests.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -310,10 +310,10 @@ export const tests = [
310310
description:
311311
'Esta prueba cifra y descifra un mensaje de tamaño configurable utilizando el algoritmo AES en modo GCM. Se simulan operaciones criptográficas del mundo real, incluyendo el uso de un nonce y una etiqueta de autenticación. Se mide el rendimiento en términos de tiempo promedio de cifrado y descifrado, así como la integridad de los datos. Esta versión está optimizada para evaluar el rendimiento criptográfico en condiciones realistas.',
312312
jsLibs: null,
313-
pyConfig: null,
313+
pyConfig: "pyscript-main.json",
314314
useNode: false,
315315
useBackend: false,
316-
inputs: null,
316+
inputs: ["num-repetitions", "message-size"],
317317
graph: false,
318318
},
319319
],

Astro-TFG/src/layouts/VersionLayout.astro

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,8 @@ const {
119119
'Tiempo de delay',
120120
'file-size':
121121
'Tamaño del archivo (MB)',
122+
'message-size':
123+
'Tamaño del mensaje (MB)',
122124
}[input] ||
123125
input
124126
.replace(/-/g, ' ')
@@ -169,6 +171,8 @@ const {
169171
'Tiempo de delay',
170172
'file-size':
171173
'Tamaño del archivo (MB)',
174+
'message-size':
175+
'Tamaño del mensaje (MB)',
172176
}[input] ||
173177
input
174178
.replace(/-/g, ' ')

0 commit comments

Comments
 (0)
0