8000 FrontEnd 4.2: Finished · JayAyAre/PyScript-vs-JavaScript@6978aca · GitHub
[go: up one dir, main page]

Skip to content

Commit 6978aca

Browse files
committed
FrontEnd 4.2: Finished
1 parent 95361e6 commit 6978aca

File tree

21 files changed

+376
-248
lines changed

21 files changed

+376
-248
lines changed

Astro-TFG/astro.config.mjs

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,28 @@
1-
// @ts-check
2-
import { defineConfig } from "astro/config";
3-
import tailwindcss from "@tailwindcss/vite";
1+
// astro.config.mjs
2+
import { defineConfig } from 'astro/config';
3+
import tailwindcss from '@tailwindcss/vite';
44

5-
// https://astro.build/config
65
export default defineConfig({
76
vite: {
8-
plugins: [tailwindcss()],
7+
server: {
8+
cors: true,
9+
},
10+
plugins: [
11+
// Este plugin inyecta COOP y COEP en el dev server
12+
{
13+
name: 'astro-dev-add-headers',
14+
configureServer(server) {
15+
server.middlewares.use((req, res, next) => {
16+
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
17+
res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp');
18+
res.setHeader('Access-Control-Allow-Origin', '*');
19+
res.setHeader('Access-Control-Allow-Methods', 'GET');
20+
next();
21+
});
22+
},
23+
},
24+
tailwindcss(),
25+
],
926
},
10-
output: 'server', // Añadir esta línea para habilitar la renderización en el servidor
11-
});
27+
output: 'server',
28+
});

Astro-TFG/public/scripts/4.2-procesamiento-datos/prueba-2/version-1/javascript/main.js

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -65,26 +65,31 @@ function doStatisticalAnalysis(size) {
6565
memoryPeak: maxMemory
6666
};
6767

68+
const outputElement = document.getElementById("javascript-output");
69+
if (!outputElement) return;
70+
outputElement.innerHTML = "";
71+
72+
6873
for (const [op, data] of Object.entries(metrics)) {
69-
if (op !== 'output') {
70-
const element = document.getElementById(`javascript-${op}`);
71-
if (element) {
72-
element.textContent =
73-
`${op.toUpperCase()} - Time: ${data.time.toFixed(2)} ms | ` +
74-
`RAM: ${data.memory.toFixed(2)} MB`;
75-
}
76-
}
74+
if (op === 'output') continue;
75+
const line = `${op.toUpperCase()} - Time av. : ${data.time.toFixed(2)} ms | RAM: ${data.memory.toFixed(2)} MB`;
76+
outputElement.innerHTML += line + "<br>";
7777
}
7878

79-
const outputElement = document.getElementById("javascript-output");
80-
if (outputElement) {
81-
outputElement.textContent =
82-
`TOTAL - Time: ${metrics['output'].totalTime.toFixed(2)} ms | ` +
83-
`RAM Peak: ${metrics['output'].memoryPeak.toFixed(2)} MB`;
84-
}
79+
outputElement.innerHTML += "<br>";
80+
const tot = metrics['output'];
81+
const totalLine = `TOTAL - Time: ${tot.totalTime.toFixed(2)} ms | RAM Peak: ${tot.memoryPeak.toFixed(2)} MB`;
82+
outputElement.innerHTML += totalLine;
8583
}
8684

87-
function runJSBenchmark() {
88-
clearCell("javascript");
89-
doStatisticalAnalysis(10_000_000);
90-
}
85+
window.runJSBenchmark = function () {
86+
clearCell("javascript-output");
87+
window.showExecutionLoader();
88+
89+
requestAnimationFrame(() => {
90+
setTimeout(() => {
91+
doStatisticalAnalysis(10_000_000);
92+
window.hideExecutionLoader();
93+
}, 0);
94+
});
95+
};

Astro-TFG/public/scripts/4.2-procesamiento-datos/prueba-2/version-1/python/main.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -67,20 +67,29 @@ def do_statistical_analysis(size):
6767
}
6868
tracemalloc.stop()
6969

70+
display("", target="pyscript-output")
71+
output_element = js.document.getElementById("pyscript-output")
72+
7073
for op, data in metrics.items():
71-
if op != 'output':
72-
display(
73-
f"{op.upper()} - Time: {data['time']:.2f} ms | RAM: {data['memory']:.2f} MB",
74-
target=f"pyscript-{op}"
75-
)
74+
if op == 'output':
75+
continue
76+
display(
77+
f"{op.upper()} - Time: {data['time']:.2f} ms | RAM: {data['memory']:.2f} MB",
78+
target=f"pyscript-output"
79+
)
80+
81+
output_element.innerHTML += f"""
82+
<br>
83+
"""
7684

77-
display(
78-
f"TOTAL - Time: {metrics['output']['total_time']:.2f} ms | "
79-
f"RAM Peak: {metrics['output']['memory_peak']:.2f} MB",
80-
target="pyscript-output"
81-
)
85+
line = f"TOTAL - Time: {metrics['output']['total_time']:.2f} ms | RAM Peak: {metrics['output']['memory_peak']:.2f} MB"
86+
display(line, target="pyscript-output")
87+
js.window.hideExecutionLoader()
8288

8389

8490
def run_py_benchmark(event):
85-
js.clearCell('pyscript')
91+
js.clearCell('pyscript-output')
8692
do_statistical_analysis(10_000_000)
93+
94+
95+
js.window.run_py_benchmark = run_py_benchmark

Astro-TFG/public/scripts/4.2-procesamiento-datos/prueba-2/version-2/javascript/main.js

Lines changed: 32 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ function initializeWorkers() {
1919
let initialized = 0;
2020

2121
for (let i = 0; i < additionalWorkers; i++) {
22-
const worker = new Worker("./javascript/worker.js");
22+
const worker = new Worker(window.location.origin + window.document.body.dataset.jsPath + "worker.js");
2323

2424
worker.onmessage = (event) => {
2525
const { id, results } = event.data;
@@ -109,60 +109,42 @@ async function runJSBenchmark(event) {
109109
displayResults(r 17AE esults);
110110
} catch (error) {
111111
console.error("Worker error:", error);
112-
displayJSText("javascript-output", `Worker Error: ${error}`);
113112
}
114113
}
115114

116115
function displayResults(results) {
117-
displayJSText(
118-
"javascript-create",
119-
`${results.create.time.toFixed(2)} ms | ${results.create.memory.toFixed(
120-
2
121-
)} MB`
122-
);
123-
displayJSText(
124-
"javascript-sum",
125-
`${results.sum.time.toFixed(2)} ms | ${results.sum.memory.toFixed(
126-
2
127-
)} MB`
128-
);
129-
displayJSText(
130-
"javascript-mean",
131-
`${results.mean.time.toFixed(2)} ms | ${results.mean.memory.toFixed(
132-
2
133-
)} MB`
134-
);
135-
displayJSText(
136-
"javascript-std",
137-
`${results.std.time.toFixed(2)} ms | ${results.std.memory.toFixed(
138-
2
139-
)} MB`
140-
);
141-
displayJSText(
142-
"javascript-output",
143-
`${results.total.average_per_execution.toFixed(2)} ms`
144-
);
145-
displayJSText(
146-
"javascript-exact",
147-
`${results.total.total_time.toFixed(2)} ms`
148-
);
149-
}
116+
let out = document.getElementById("javascript-output");
117+
for (const op of ['create', 'sum', 'mean', 'std']) {
118+
const data = results[op];
119+
const time = Math.round(data.time * 100) / 100;
120+
const mem = Math.round(data.memory * 100) / 100;
121+
const line = `${op.toUpperCase()} - Time: ${time.toFixed(2)} ms | RAM: ${mem.toFixed(2)} MB`;
122+
123+
const div = document.createElement('div');
124+
div.textContent = line;
125+
out.appendChild(div);
126+
}
150127

151-
function clearCell(prefix) {
152-
const operations = ["create", "sum", "mean", "std", "output", "exact"];
153-
operations.forEach((op) => {
154-
const element = document.getElementById(`${prefix}-${op}`);
155-
if (element) {
156-
element.innerHTML = "";
157-
}
158-
});
128+
const avg = Math.round(results.total.average_per_execution * 100) / 100;
129+
const avgDiv = document.createElement('div');
130+
avgDiv.textContent = `Av. Time: ${avg.toFixed(2)} ms`;
131+
out.appendChild(avgDiv);
132+
133+
const tot = Math.round(results.total.total_time * 100) / 100;
134+
const totDiv = document.createElement('div');
135+
totDiv.textContent = `TOTAL - Time: ${tot.toFixed(2)} ms`;
136+
out.appendChild(totDiv);
159137
}
160138

161-
function displayJSText(elementId, text) {
162-
const element = document.getElementById(elementId);
163-
if (element) {
164-
element.textContent += text;
165-
} else {
166-
console.warn(`Element with ID ${elementId} not found.`);
139+
window.runJSBenchmark = async function () {
140+
clearCell("javascript-output");
141+
window.showExecutionLoader();
142+
143+
await new Promise(requestAnimationFrame);
144+
145+
try {
146+
await runJSBenchmark();
147+
} finally {
148+
window.hideExecutionLoader();
167149
}
168-
}
150+
};
Lines changed: 2 additions & 2 deletions
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": ["numpy"]
6-
}
6+
}

Astro-TFG/public/scripts/4.2-procesamiento-datos/prueba-2/version-2/python/main.py

Lines changed: 32 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -9,24 +9,31 @@
99

1010

1111
async def initialize_worker():
12-
global workers, workers_ready
13-
num_workers = int(js.document.querySelector(
14-
"#parallel-workers-pyscript").value)
15-
16-
if len(workers) > num_workers:
17-
workers = workers[:num_workers]
18-
elif len(workers) < num_workers:
19-
additional_workers = num_workers - len(workers)
20-
for _ in range(additional_workers):
21-
worker = PyWorker(
22-
"./python/worker.py",
23-
type="pyodide",
24-
config="./json/pyscript-worker.json"
25-
)
12+
global workers
13+
14+
try:
15+
num_workers = int(js.document.querySelector(
16+
"#parallel-workers-pyscript").value) or 1
17+
if num_workers < 1:
18+
num_workers = 1
19+
20+
if len(workers) > num_workers:
21+
workers = workers[:num_workers]
22+
elif len(workers) < num_workers:
23+
to_create = num_workers - len(workers)
24+
origin = js.window.location.origin
25+
py_path = js.window.document.body.dataset.pyPath
26+
27+
for _ in range(to_create):
28+
worker = PyWorker(
29+
f"{origin}{py_path}worker.py",
30+
type="pyodide",
31+
config=f"{origin}{py_path.replace('python', 'json')}pyscript-worker.json"
32+
)
2633
await worker.ready
2734
workers.append(worker)
28-
29-
workers_ready = True
35+
except Exception as e:
36+
display(f"Error al crear workers: {e}", target="pyscript-output")
3037

3138
asyncio.create_task(initialize_worker())
3239

@@ -76,6 +83,7 @@ async def run_py_benchmark(event):
7683
'total_time': (time.perf_counter() - start_time) * 1000
7784
}
7885

86+
js.window.hideExecutionLoader()
7987
update_ui(results)
8088

8189
except Exception as e:
@@ -85,20 +93,21 @@ async def run_py_benchmark(event):
8593
def update_ui(results):
8694
for operation in ['create', 'sum', 'mean', 'std']:
8795
display(
88-
f"{results[operation]['time']:.2f} ms | {results[operation]['memory']: .2f} MB",
89-
target=f"pyscript-{operation}"
90-
)
96+
f"{operation.upper()} - Time: {results[operation]['time']:.2f} ms | RAM: {results[operation]['memory']:.2f} MB", target D76A =f"pyscript-output")
9197

9298
display(
93-
f"{results['total']['average_per_execution']:.2f} ms",
99+
f"Av. Time: {results['total']['average_per_execution']:.2f} ms",
94100
target="pyscript-output"
95101
)
96102
display(
97-
f"{results['total']['total_time']:.2f} ms",
98-
target="pyscript-exact"
103+
f"TOTAL - Time: {results['total']['total_time']:.2f} ms",
104+
target="pyscript-output"
99105
)
100106

101107

102108
def js_run_py_benchmark(event):
103-
js.clearCell("pyscript")
109+
js.clearCell('pyscript-output')
104110
asyncio.ensure_future(run_py_benchmark(None))
111+
112+
113+
js.window.run_py_benchmark = js_run_py_benchmark

0 commit comments

Comments
 (0)
0