8000 Test 4.6\1: finished · JayAyAre/PyScript-vs-JavaScript@9c65c60 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9c65c60

Browse files
committed
Test 4.6\1: finished
1 parent 81c01c2 commit 9c65c60

File tree

11 files changed

+557
-0
lines changed

11 files changed

+557
-0
lines changed

4.6-patrones/prueba-1/.rnd

1 KB
Binary file not shown.

4.6-patrones/prueba-1/cert.pem

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
-----BEGIN CERTIFICATE-----
2+
MIIDRzCCAi+gAwIBAgIJANMj6R5DLofFMA0GCSqGSIb3DQEBBQUAMDoxCzAJBgNV
3+
BAYTAkVTMRIwEAYDVQQIEwlCZXJrc2hpcmUxFzAVBgNVBAoTDk15IENvbXBhbnkg
4+
THRkMB4XDTI1MDQxODEzNDc1NVoXDTI2MDQxODEzNDc1NVowOjELMAkGA1UEBhMC
5+
RVMxEjAQBgNVBAgTCUJlcmtzaGlyZTEXMBUGA1UEChMOTXkgQ29tcGFueSBMdGQw
6+
ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDB7w5U3dNVAZ9HgAbIvGUr
7+
O7NxfugrW3ZX03NyxJfqbA3GQBmLZv3Y139xXoVd39CpLu0REYl8St+b7nHEBA8g
8+
FdKZgCwyuI2PcN4Ewk+DZ9QUxjOVuj6bfsyOijNc7VJ35i4NH+Wj/t6079MJmn96
9+
DeRHhFFe+io6j8TfNXIblam8p2t03A2qAjsZRuXLkclZ5E7FJhVKEWnU6Wll7oI5
10+
9kqN8EmzWuV2RvGnFOvjR6QDaONAX8tMGC9cfvqE6HJ6zLX5FikLEUj3dSPDj8Wt
11+
QIelTuxBFK7CPoaNmconWIx2t3b7crvZ4Zxa+BHfwmuxorBpy+HIHgFZTddo1jL9
12+
AgMBAAGjUDBOMB0GA1UdDgQWBBSjaGpisyeSNA0aYM6eEVVzp2tsTTAfBgNVHSME
13+
GDAWgBSjaGpisyeSNA0aYM6eEVVzp2tsTTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3
14+
DQEBBQUAA4IBAQC5thww0G4R9wPampj/9CrtEku4EHgapuT7gMt3iQ0imUEUBh3g
15+
6PEkOAt4kukIc6V/8+p+kX2g+eXdTvOmNuWxjKofRXvt7C148rgvvTuah74AJtfU
16+
95untquyzGpVi/LAN3xMspqULM6ICXo27cKaFv38vYHLLDNKM7So+KCAQ/O8jtZn
17+
wJGN/t/MerPTRDFBhEkNzz4n2pUvvVOd9ccRbnTL2Ux89hbL9wgo7E372NAyJmRz
18+
ZqKIu+S63hSfck9HepM+dNvlf85edgvOzjB5hp1g1MJrFTDYYzZi2RE+tG+KRRVP
19+
pntJ1xn1GCZ2ShbpoXZPn54FtmtgAVIF/EDK
20+
-----END CERTIFICATE-----

4.6-patrones/prueba-1/index.html

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<title>Benchmarking: JavaScript vs PyScript</title>
7+
<script type="importmap">
8+
{
9+
"imports": {
10+
"ml-random-forest": "https://cdn.jsdelivr.net/npm/ml-random-forest@2.1.0/dist/random-forest.js"
11+
}
12+
}
13+
</script>
14+
15+
<script type="module" src="javascript/main.js"></script>
16+
17+
<!-- 3) Psist Script Core -->
18+
<script type="module" src="https://pyscript.net/releases/2024.8.1/core.js"></script>
19+
<link rel="stylesheet" href="https://pyscript.net/releases/2024.8.1/core.css">
20+
21+
22+
<script>
23+
if (!crypto.randomUUID) {
24+
crypto.randomUUID = function() {
25+
// Genera un UUID v4
26+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
27+
const r = Math.random() * 16 | 0;
28+
const v = c === 'x' ? r : (r & 0x3 | 0x8);
29+
return v.toString(16);
30+
});
31+
}
32+
}
33+
document.addEventListener('py:ready', () => {
34+
document.getElementById("run-button-py").disabled = false;
35+
36+
document.getElementById("run-button-py").textContent = 'Run in PyScript';
37+
console.log('PyScript fully loaded');
38+
});
39+
let pyTimer = null;
40+
let pyStartTime = 0;
41+
42+
function startPyTimer() {
43+
pyStartTime = performance.now();
44+
const timerElement = document.getElementById("py-timer-display");
45+
46+
function updateTimer() {
47+
if (!pyTimer) return;
48+
49+
const elapsedMs = performance.now() - pyStartTime;
50+
const elapsed = (elapsedMs / 1000).toFixed(3);
51+
timerElement.textContent = `PyScript Timer: ${elapsed} s`;
52+
53+
pyTimer = requestAnimationFrame(updateTimer);
54+
}
55+
56+
cancelAnimationFrame(pyTimer);
57+
pyTimer = requestAnimationFrame(updateTimer);
58+
}
59+
60+
function stopPyTimer() {
61+
cancelAnimationFrame(pyTimer);< 10000 /span>
62+
pyTimer = null;
63+
64+
const elapsedMs = performance.now() - pyStartTime;
65+
const elapsed = (elapsedMs / 1000).toFixed(3);
66+
document.getElementById("py-timer-display").textContent = `PyScript Timer: ${elapsed} s`;
67+
}
68+
let startTime = performance.now();
69+
70+
document.addEventListener('py:ready', () => {
71+
let endTime = performance.now();
72+
let loadTime = endTime - startTime;
73+
document.getElementById("output").innerText += `PLT: ${loadTime.toFixed(2)} ms`;
74+
});
75+
76+
function clearCell(elementId) {
77+
const operations = ['output', 'exact'];
78+
operations.forEach(op => {
79+
const element = document.getElementById(`${elementId}-${op}`);
80+
if (element) {
81+
element.innerHTML = "";
82+
}
83+
});
84+
}
85+
</script>
86+
<body>
87+
<script type="py" src="python/main.py" config="json/pyscript-main.json"></script>
88+
<script>
89+
function clearMetrics(prefix) {
90+
["worker","training","inference","accuracy","memory","total"]
91+
.forEach(id => document.getElementById(`${prefix}-${id}`).textContent = "");
92+
}
93+
</script>
94+
<h1>Benchmark: cryptographic proofs</h1>
95+
<h2 id="output"></h2>
96+
97+
<div>
98+
<label>Repetitions:</label>
99+
<input type="number" id="num-repetitions-js" value="5" min="1">
100+
<button id="run-button-js" onclick="javascriptBenchmark()">Run JavaScript</button>
101+
</div>
102+
103+
104+
<div>
105+
<label>Repetitions:</label>
106+
<input type="number" id="num-repetitions-py" value="5" min="1">
107+
<button id="run-button-py" py-click="launch_worker" disabled>Run PyScript (Loading...)</button>
108+
</div>
109+
110+
111+
<h2 id="js-timer-display">JS Timer: 0.00 s</h2>
112+
<h2 id="py-timer-display">PyScript Timer: 0.00 s</h2>
113+
<div id="debug-console"></div>
114+
115+
116+
<table id="metrics-container">
117+
<thead>
118+
<tr>
119+
<th>Metric</th><th>JavaScript</th><th>PyScript</th>
120+
</tr>
121+
</thead>
122+
<tbody>
123+
<tr>
124+
<td>Worker init</td>
125+
<td id="javascript-worker"></td>
126+
<td id="pyscript-worker"></td>
127+
</tr>
128+
<tr>
129+
<td>Av. Training time</td>
130+
<td id="javascript-training"></td>
131+
<td id="pyscript-training"></td>
132+
</tr>
133+
<tr>
134+
<td>Av. Inference time</td>
135+
<td id="javascript-inference"></td>
136+
<td id="pyscript-inference"></td>
137+
</tr>
138+
<tr>
139+
<td>Av. Accuracy</td>
140+
<td id="javascript-accuracy"></td>
141+
<td id="pyscript-accuracy"></td>
142+
</tr>
143+
<tr>
144+
<td>Model size</td>
145+
<td id="javascript-memory"></td>
146+
<td id="pyscript-memory"></td>
147+
</tr>
148+
<tr>
149+
<td>Total time</td>
150+
<td id="javascript-total"></td>
151+
<td id="pyscript-total"></td>
152+
</tr>
153+
</tbody>
154+
</table>
155+
</body>
156+
</html>
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// main.js
2+
let worker = null;
3+
let jsTimer = null;
4+
let jsStartTime = 0;
5+
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+
}
18+
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`;
26+
}
27+
28+
async function javascriptBenchmark() {
29+
try {
30+
startJsTimer();
31+
clearCell("javascript");
32+
33+
// measure Worker init time
34+
const startWorkerTime = performance.now();
35+
if (!worker) {
36+
worker = new Worker(new URL("worker.js", import.meta.url), {
37+
type: "module",
38+
});
39+
}
40+
const workerTime = performance.now() - startWorkerTime;
41+
document.getElementById(
42+
"javascript-worker"
43+
).textContent = `${workerTime.toFixed(2)} ms`;
44+
45+
// read repetitions
46+
const repetitions = parseInt(
47+
document.getElementById("num-repetitions-js").value,
48+
10
49+
);
50+
const id = `js-${Date.now()}`;
51+
52+
// dispatch to worker
53+
const resultJson = await new Promise((resolve, reject) => {
54+
function onMessage(e) {
55+
if (e.data.id !== id) return;
56+
worker.removeEventListener("message", onMessage);
57+
if (e.data.error) {
58+
reject(new Error(e.data.error));
59+
} else {
60+
resolve(e.data.json);
61+
}
62+
}
63+
worker.addEventListener("message", onMessage);
64+
worker.postMessage({
65+
id,
66+
type: "js_run_js_benchmark",
67+
workerTime,
68+
repetitions,
69+
});
70+
});
71+
72+
const r = JSON.parse(resultJson);
73+
displayResult(r);
74+
} catch (err) {
75+
console.error("Benchmark error:", err);
76+
document.getElementById(
77+
"javascript-output"
78+
).textContent = `Error: ${err.message}`;
79+
} finally {
80+
stopJsTimer();
81+
}
82+
}
83+
84+
function clearCell(prefix) {
85+
["worker", "training", "inference", "accuracy", "memory", "total"].forEach(
86+
(id) => {
87+
const el = document.getElementById(`${prefix}-${id}`);
88+
if (el) el.textContent = "";
89+
}
90+
);
91+
}
92+
93+
function displayResult(r) {
94+
document.getElementById(
95+
"javascript-training"
96+
).textContent = `${r.training_time_ms.toFixed(2)} ms`;
97+
document.getElementById(
98+
"javascript-inference"
99+
).textContent = `${r.inference_time_ms.toFixed(2)} ms`;
100+
document.getElementById(
101+
"javascript-accuracy"
102+
).textContent = `${r.accuracy.toFixed(2)} %`;
103+
document.getElementById(
104+
"javascript-memory"
105+
).textContent = `${r.model_size_mb.toFixed(2)} MB`;
106+
document.getElementById(
107+
"javascript-total"
108+
).textContent = `${r.overall_time_ms.toFixed(2)} ms`;
109+
}
110+
111+
// expose globally
112+
window.javascriptBenchmark = javascriptBenchmark;
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import { RandomForestClassifier as RFClassifier } from "https://jspm.dev/ml-random-forest";
2+
3+
self.addEventListener("message", async (e) => {
4+
const { id, type, workerTime, repetitions } = e.data;
5+
if (type !== "js_run_js_benchmark") return;
6+
7+
// 1) Descarga y parseo del CSV de Iris
8+
const IRIS_CSV_URL =
9+
"https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv";
10+
const resp = await fetch(IRIS_CSV_URL);
11+
const raw = await resp.text();
12+
const rows = raw.trim().split("\n").slice(1);
13+
14+
// 2) Creamos IrisDataset con la API que quieres
15+
const IrisDataset = {
16+
getNumbers: () => rows.map((r) => r.split(",").slice(0, 4).map(Number)),
17+
getClasses: () => rows.map((r) => r.split(",")[4]),
18+
getDistinctClasses: () =>
19+
Array.from(new Set(rows.map((r) => r.split(",")[4]))),
20+
};
21+
22+
// 3) Obtenemos trainingSet y labels
23+
const trainingSet = IrisDataset.getNumbers();
24+
const predictions = IrisDataset.getClasses().map((c) =>
25+
IrisDataset.getDistinctClasses().indexOf(c)
26+
);
27+
28+
// 4) Configuración del RF (100 árboles para igualar sklearn)
29+
const options = {
30+
seed: 3,
31+
maxFeatures: 1.0,
32+
replacement: true,
33+
nEstimators: 100,
34+
};
35+
36+
let totalTrain = 0,
37+
totalInfer = 0,
38+
totalAcc = 0,
39+
clf;
40+
41+
const t0All = performance.now();
42+
for (let i = 0; i < repetitions; i++) {
43+
// entrenamiento
44+
const t0 = performance.now();
45+
clf = new RFClassifier(options);
46+
clf.train(trainingSet, predictions);
47+
totalTrain += performance.now() - t0;
48+
49+
// inferencia
50+
const t1 = performance.now();
51+
const preds = clf.predict(trainingSet);
52+
totalInfer += performance.now() - t1;
53+
54+
// precisión
55+
const correct = preds.reduce(
56+
(sum, p, idx) => sum + (p === predictions[idx] ? 1 : 0),
57+
0
58+
);
59+
totalAcc += (correct / predictions.length) * 100;
60+
}
61+
const overall = performance.now() - t0All;
62+
63+
// 5) Serializa el modelo para medir tamaño
64+
const modelJson = JSON.stringify(clf.toJSON());
65+
const modelSizeMB = new Blob([modelJson]).size / 1024 ** 2;
66+
67+
// 6) Envía el resultado de vuelta
68+
const result = {
69+
training_time_ms: totalTrain / repetitions,
70+
inference_time_ms: totalInfer / repetitions,
71+
accuracy: totalAcc / repetitions,
72+
model_size_mb: modelSizeMB,
73+
overall_time_ms: overall,
74+
};
75+
self.postMessage({ id, json: JSON.stringify(result) });
76+
});
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"files": {
3+
"/python/worker.py": "worker.py"
4+
}
5+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"packages": ["scikit-learn"]
3+
}

0 commit comments

Comments
 (0)
0