8000 Test 4.4/2: Finished · JayAyAre/PyScript-vs-JavaScript@197ce6f · GitHub
[go: up one dir, main page]

Skip to content

Commit 197ce6f

Browse files
committed
Test 4.4/2: Finished
1 parent 80eb358 commit 197ce6f

File tree

25 files changed

+948
-209
lines changed

25 files changed

+948
-209
lines changed

4.4-manejo-peticiones-http/prueba-1/frontend_server.py

Lines changed: 0 additions & 28 deletions
This file was deleted.

4.4-manejo-peticiones-http/prueba-1/index.html

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
<link rel="stylesheet" href="https://pyscript.net/releases/2024.8.1/core.css">
1111

1212
<script src="javascript/main.js" defer></script>
13-
<script src="https://cdn.plot.ly/plotly-3.0.1.min.js" charset="utf-8"></script>
1413

1514
<script>
1615
if (!crypto.randomUUID) {
@@ -79,20 +78,38 @@
7978
<body>
8079
<script type="py" src="python/main.py" config="json/pyscript-main.json"></script>
8180

82-
<h1>Benchmark: Concurrent Requests via PyScript</h1>
81+
<h1>Benchmark: Concurrent Requests (PyScript/JavaScript)</h1>
8382
<h2 id="output"></h2>
83+
8484
<div>
85-
<label for="num-requests">Número de solicitudes:</label>
86-
<input type="number" id="num-requests-py" value="5" min="1">
85+
<div>
86+
<label for="num-requests">Número de solicitudes:</label>
87+
<input type="number" id="num-requests-js" value="5" min="1">
88+
</div>
89+
<div>
90+
<label for="request-delay">Retardo F438 por solicitud (ms):</label>
91+
<input type="number" id="request-delay-js" value="100" min="0">
92+
</div>
93+
<button id="run-button-js" onclick="javascriptBenchmark()">Run JavaScript</button>
8794
</div>
95+
96+
8897
<div>
89-
<label for="request-delay">Retardo por solicitud (ms):</label>
90-
<input type="number" id="request-delay-py" value="100" min="0">
98+
<div>
99+
<label for="num-requests">Número de solicitudes:</label>
100+
<input type="number" id="num-requests-py" value="5" min="1">
101+
</div>
102+
<div>
103+
<label for="request-delay">Retardo por solicitud (ms):</label>
104+
<input type="number" id="request-delay-py" value="100" min="0">
105+
</div>
106+
<button id="run-button-py" py-click="launch_worker" disabled>Run PyScript (Loading...)</button>
91107
</div>
92108

93-
<button id="run-button-py" py-click="launch_worker" disabled>Run Benchmark (Loading...)</button>
94109

95-
<h2 id="py-timer-display">Timer: 0.00 s</h2>
110+
<h2 id="js-timer-display">JS Timer: 0.00 s</h2>
111+
<h2 id="py-timer-display">PyScript Timer: 0.00 s</h2>
112+
<div id="debug-console"></div>
96113

97114

98115
<table id="metrics-container">
Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,34 @@
11
const express = require("express");
22
const cors = require("cors");
3-
43
const app = express();
5-
const PORT = 5002; // Asegúrate que este puerto coincida con el configurado en el Python
4+
const port = 5002;
65

76
app.use(cors());
87

8+
function sleepBlocking(ms) {
9+
const start = Date.now();
10+
while (Date.now() - start < ms) {}
11+
}
12+
913
app.get("/mock-api/:delay", (req, res) => {
1014
const delay = parseInt(req.params.delay, 10);
11-
setTimeout(() => {
12-
const data = Array.from({ length: 1000 }, (_, i) => ({
13-
id: i,
14-
value: i * 10,
15-
}));
16-
res.json({
17-
status: "success",
18-
delay,
19-
data,
20-
});
21-
}, delay);
15+
16+
if (delay > 0) {
17+
sleepBlocking(delay);
18+
}
19+
20+
const data = Array.from({ length: 10 }, (_, i) => ({
21+
id: i,
22+
value: Math.random(),
23+
}));
24+
25+
res.json({
26+
status: "success",
27+
delay: delay,
28+
data: data,
29+
});
2230
});
2331

24-
app.listen(PORT, () => {
25-
console.log(`JavaScript API corriendo en http://localhost:${PORT}`);
32+
app.listen(port, () => {
33+
console.log(`Server is running on http://localhost:${port}`);
2634
});
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
let worker = null;
2+
const JAVASCRIPT_SERVER = "http://localhost:5002";
3+
4+
async function javascriptBenchmark() {
5+
try {
6+
window.clearCell("javascript");
7+
startJsTimer();
8+
9+
const num_requests = parseInt(
10+
document.getElementById("num-requests-js").value,
11+
10
12+
);
13+
const delay = parseInt(
14+
document.getElementById("request-delay-js").value,
15+
10
16+
);
17+
18+
const urls = Array.from(
19+
{ length: num_requests },
20+
(_, i) => `${JAVASCRIPT_SERVER}/mock-api/${delay}`
21+
);
22+
23+
let start_time_worker = performance.now();
24+
if (!worker) {
25+
worker = new Worker("javascript/worker.js");
26+
}
27+
let worker_time = performance.now() - start_time_worker;
28+
29+
worker.onmessage = function (e) {
30+
const { total_time, avg_time, results } = e.data;
31+
updateResults(total_time, avg_time, worker_time, results);
32+
stopJsTimer();
33+
};
34+
35+
const start_time = performance.now();
36+
37+
worker.postMessage({ num_requests, delay, worker_time });
38+
} catch (e) {
39+
console.error(e);
40+
}
41+
}
42+
43+
function updateResults(total_time, avg_time, worker_time, results) {
44+
const output = document.getElementById("javascript-output");
45+
46+
let lastValueDisplay = "No valid data in the last response.";
47+
if (
48+
results &&
49+
results.length > 0 &&
50+
results[results.length - 1] &&
51+
results[results.length - 1].data
52+
) {
53+
const last_value = results[results.length - 1].data[9].value;
54+
lastValueDisplay = `Last Value: ${last_value.toFixed(6)}`;
55+
}
56+
57+
output.innerHTML = `
58+
<div>Worker Time: ${worker_time.toFixed(2)} ms</div>
59+
<div>Avg Request Time: ${avg_time.toFixed(2)} ms</div>
60+
<div>Total Time: ${total_time.toFixed(2)} ms</div>
61+
<div>Total Finished Requests: ${results.length}</div>
62+
<div>${lastValueDisplay}</div>
63+
`;
64+
}
65+
66+
let jsTimer = null;
67+
let jsStartTime = 0;
68+
69+
function startJsTimer() {
70+
jsStartTime = performance.now();
71+
const timerElement = document.getElementById("js-timer-display");
72+
73+
function updateTimer() {
74+
if (!jsTimer) return;
75+
76+
const elapsedMs = performance.now() - jsStartTime;
77+
const elapsed = (elapsedMs / 1000).toFixed(3);
78+
timerElement.textContent = `JS Timer: ${elapsed} s`;
79+
80+
jsTimer = requestAnimationFrame(updateTimer);
81+
}
82+
83+
cancelAnimationFrame(jsTimer);
84+
jsTimer = requestAnimationFrame(updateTimer);
85+
}
86+
87+
function stopJsTimer() {
88+
cancelAnimationFrame(jsTimer);
89+
jsTimer = null;
90+
91+
const elapsedMs = performance.now() - jsStartTime;
92+
const elapsed = (elapsedMs / 1000).toFixed(3);
93+
document.getElementById(
94+
"js-timer-display"
95+
).textContent = `JS Timer: ${elapsed} s`;
96+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
self.onmessage = async function (e) {
2+
const { num_requests, delay } = e.data;
3+
4+
const results = [];
5+
const individualTimes = [];
6+
7+
const fetchWithTiming = async () => {
8+
const start = performance.now();
9+
try {
10+
const res = await fetch(`http://localhost:5002/mock-api/${delay}`);
11+
const json = await res.json();
12+
results.push(json);
13+
} catch (e) {
14+
results.push(null);
15+
} finally {
16+
const end = performance.now();
17+
individualTimes.push(end - start);
18+
}
19+
};
20+
21+
const fetchPromises = Array.from({ length: num_requests }, () =>
22+
fetchWithTiming()
23+
);
24+
25+
const start_time = performance.now();
26+
await Promise.all(fetchPromises);
27+
const total_time = performance.now() - start_time;
28+
29+
const avg_time =
30+
individualTimes.length > 0
31+
? individualTimes.reduce((acc, t) => acc + t, 0) /
32+
individualTimes.length
33+
: 0;
34+
35+
self.postMessage({
36+
total_time,
37+
avg_time,
38+
results,
39+
});
40+
};
Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
{
2-
"packages": ["aiohttp"]
32
}

4.4-manejo-peticiones-http/prueba-1/python/app.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import numpy as np
12
from flask import Flask, jsonify
23
from flask_cors import CORS
34
import time
@@ -8,11 +9,15 @@
89

910
@app.route('/mock-api/<int:delay>')
1011
def mock_api(delay):
11-
time.sleep(delay/1000)
12+
if delay != 0:
13+
time.sleep(delay / 1000)
14+
15+
data = [{"id": i, "value": np.random.rand()} for i in range(10)]
16+
1217
return jsonify({
1318
"status": "success",
1419
"delay": delay,
15-
"data": [{"id": i, "value": i*10} for i in range(1000)]
20+
"data": data
1621
})
1722

1823

0 commit comments

Comments
 (0)
0