Repository navigation
Expand file tree
/
Copy pathbenchmark.js
More file actions
503 lines (419 loc) · 17.5 KB
/
Copy pathbenchmark.js
File metadata and controls
503 lines (419 loc) · 17.5 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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// Main Benchmark Controller
class BenchmarkController {
constructor() {
this.currentTest = null;
this.gpuTest = null;
this.cpuTest = null;
this.results = null;
this.gpuRenderer = null;
this.init();
}
init() {
// Test selection
document.getElementById('cpuCard').addEventListener('click', () => this.selectTest('cpu'));
document.getElementById('gpuCard').addEventListener('click', () => this.selectTest('gpu'));
// Control buttons
document.getElementById('startBtn').addEventListener('click', () => this.start());
document.getElementById('stopBtn').addEventListener('click', () => this.stop());
document.getElementById('resetBtn').addEventListener('click', () => this.reset());
document.getElementById('shareBtn').addEventListener('click', () => this.share());
document.getElementById('copyBtn').addEventListener('click', () => this.copyShareLink());
}
selectTest(testType) {
this.currentTest = testType;
// Update UI
document.getElementById('cpuCard').classList.toggle('active', testType === 'cpu');
document.getElementById('gpuCard').classList.toggle('active', testType === 'gpu');
document.getElementById('cpuArea').classList.toggle('active', testType === 'cpu');
document.getElementById('gpuArea').classList.toggle('active', testType === 'gpu');
document.getElementById('controlsCard').style.display = 'block';
document.getElementById('scoreDisplay').style.display = 'none';
// Initialize the selected test
if (testType === 'gpu' && !this.gpuRenderer) {
this.initGPUTest();
} else if (testType === 'cpu' && !this.cpuTest) {
this.initCPUTest();
}
this.reset();
}
initGPUTest() {
// Check if ParticleRenderer is already loaded
if (typeof ParticleRenderer !== 'undefined') {
const canvas = document.getElementById('benchmarkCanvas');
this.gpuRenderer = new ParticleRenderer(canvas);
this.gpuTest = new GPUBenchmark(this.gpuRenderer, () => this.onBenchmarkComplete());
} else {
// Load the GPU test script
const script = document.createElement('script');
script.src = 'gpu-test.js';
script.onload = () => {
const canvas = document.getElementById('benchmarkCanvas');
this.gpuRenderer = new ParticleRenderer(canvas);
this.gpuTest = new GPUBenchmark(this.gpuRenderer, () => this.onBenchmarkComplete());
};
document.body.appendChild(script);
}
}
initCPUTest() {
this.cpuTest = new CPUBenchmark(() => this.onBenchmarkComplete());
}
onBenchmarkComplete() {
// Called when benchmark finishes automatically
this.stop();
}
start() {
document.getElementById('startBtn').disabled = true;
document.getElementById('stopBtn').disabled = false;
document.getElementById('scoreDisplay').style.display = 'none';
document.getElementById('shareSection').style.display = 'none';
if (this.currentTest === 'gpu' && this.gpuTest) {
this.gpuTest.start();
} else if (this.currentTest === 'cpu' && this.cpuTest) {
this.cpuTest.start();
}
}
stop() {
document.getElementById('startBtn').disabled = false;
document.getElementById('stopBtn').disabled = true;
if (this.currentTest === 'gpu' && this.gpuTest) {
this.gpuTest.stop();
this.results = this.gpuTest.getResults();
} else if (this.currentTest === 'cpu' && this.cpuTest) {
this.cpuTest.stop();
this.results = this.cpuTest.getResults();
}
this.displayResults();
// Automatically save to leaderboard
this.autoSaveToLeaderboard();
}
reset() {
document.getElementById('startBtn').disabled = false;
document.getElementById('stopBtn').disabled = true;
document.getElementById('progressBar').style.width = '0%';
document.getElementById('scoreDisplay').style.display = 'none';
document.getElementById('shareSection').style.display = 'none';
document.getElementById('shareUrl').style.display = 'none';
document.getElementById('leaderboardNotice').style.display = 'none';
document.getElementById('metricsGrid').innerHTML = '';
if (this.currentTest === 'gpu' && this.gpuTest) {
this.gpuTest.reset();
} else if (this.currentTest === 'cpu' && this.cpuTest) {
this.cpuTest.reset();
}
this.results = null;
this.shareCode = null;
}
displayResults() {
if (!this.results) return;
document.getElementById('scoreValue').textContent = this.results.score.toLocaleString();
document.getElementById('scoreLabel').textContent = `${this.currentTest.toUpperCase()} Performance Score`;
document.getElementById('scoreRating').textContent = this.results.rating;
document.getElementById('scoreDisplay').style.display = 'block';
document.getElementById('shareSection').style.display = 'block';
// Display metrics
const metricsGrid = document.getElementById('metricsGrid');
metricsGrid.innerHTML = '';
Object.entries(this.results.metrics).forEach(([key, value]) => {
const metricCard = document.createElement('div');
metricCard.className = 'metric-card';
metricCard.innerHTML = `
<div class="metric-value">${value}</div>
<div class="metric-label">${key}</div>
`;
metricsGrid.appendChild(metricCard);
});
}
async autoSaveToLeaderboard() {
if (!this.results) return;
const shareBtn = document.getElementById('shareBtn');
shareBtn.textContent = 'Saving...';
shareBtn.disabled = true;
try {
const response = await fetch('api.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
action: 'save_result',
test_type: this.currentTest,
...this.results
})
});
const data = await response.json();
if (data.success) {
this.shareCode = data.share_code;
const shareUrl = `${window.location.origin}/benchmark/result.php?id=${data.share_code}`;
document.getElementById('shareLink').textContent = shareUrl;
document.getElementById('shareUrl').style.display = 'flex';
document.getElementById('leaderboardNotice').style.display = 'block';
shareBtn.textContent = 'Copy Link';
shareBtn.disabled = false;
} else {
shareBtn.textContent = 'Save Failed';
document.getElementById('leaderboardNotice').style.display = 'none';
console.error('Failed to save results:', data.error);
}
} catch (error) {
console.error('Auto-save error:', error);
shareBtn.textContent = 'Save Failed';
}
}
async share() {
// Now just copies the link since it's already saved
this.copyShareLink();
}
copyShareLink() {
const shareLink = document.getElementById('shareLink').textContent;
navigator.clipboard.writeText(shareLink).then(() => {
const message = document.getElementById('shareMessage');
message.style.display = 'block';
setTimeout(() => {
message.style.display = 'none';
}, 2000);
});
}
}
// GPU Benchmark Manager
class GPUBenchmark {
constructor(renderer, onComplete) {
this.renderer = renderer;
this.onComplete = onComplete;
this.running = false;
this.startTime = 0;
this.frameCount = 0;
this.visualFrameCount = 0;
this.fpsHistory = [];
this.benchmarkDuration = 30000;
this.lastFrameTime = 0;
this.lastVisualFrameTime = 0;
this.frameTimestamps = [];
this.rendersPerFrame = 8;
this.metrics = {
avgFps: 0,
minFps: Infinity,
maxFps: 0,
totalFrames: 0
};
}
start() {
this.running = true;
this.startTime = performance.now();
this.frameCount = 0;
this.visualFrameCount = 0;
this.fpsHistory = [];
this.frameTimestamps = [];
this.lastFrameTime = this.startTime;
this.lastVisualFrameTime = this.startTime;
this.metrics = {
avgFps: 0,
minFps: Infinity,
maxFps: 0,
totalFrames: 0
};
this.animate();
}
animate() {
if (!this.running) return;
const currentTime = performance.now();
this.visualFrameCount++;
const visualDeltaTime = Math.max(currentTime - this.lastVisualFrameTime, 1);
const visualFps = Math.min(1000 / visualDeltaTime, 9999);
this.fpsHistory.push(visualFps);
if (visualFps < this.metrics.minFps) this.metrics.minFps = visualFps;
if (visualFps > this.metrics.maxFps) this.metrics.maxFps = visualFps;
this.lastVisualFrameTime = currentTime;
for (let i = 0; i < this.rendersPerFrame; i++) {
const renderTime = performance.now();
this.frameTimestamps.push(renderTime);
this.renderer.time += 0.016;
this.renderer.mode = Math.floor((renderTime - this.startTime) / 10000) % 3;
this.renderer.render();
this.frameCount++;
}
if (this.visualFrameCount % 10 === 0) {
const recentFps = this.fpsHistory.slice(-60);
const avgRecent = recentFps.reduce((a, b) => a + b, 0) / recentFps.length;
document.getElementById('fpsCounter').textContent = `FPS: ${Math.round(avgRecent)}`;
}
const progress = Math.min(((currentTime - this.startTime) / this.benchmarkDuration) * 100, 100);
document.getElementById('progressBar').style.width = `${progress}%`;
if (currentTime - this.startTime >= this.benchmarkDuration) {
this.stop();
if (this.onComplete) this.onComplete();
return;
}
requestAnimationFrame(() => this.animate());
}
stop() {
this.running = false;
this.calculateMetrics();
}
calculateMetrics() {
const validFps = this.fpsHistory.filter(fps => !isNaN(fps) && isFinite(fps) && fps > 0);
if (validFps.length === 0) return;
const avgFps = validFps.reduce((a, b) => a + b, 0) / validFps.length;
const minFps = this.metrics.minFps === Infinity ? 0 : this.metrics.minFps;
const maxFps = Math.max(this.metrics.maxFps, avgFps);
this.metrics.avgFps = Math.round(avgFps);
this.metrics.minFps = Math.round(minFps);
this.metrics.maxFps = Math.round(maxFps);
this.metrics.totalFrames = this.frameCount;
}
getResults() {
const consistency = this.metrics.maxFps > 0 ? 1 - Math.min((this.metrics.maxFps - this.metrics.minFps) / this.metrics.maxFps, 0.5) : 0;
const score = Math.round((this.metrics.avgFps * 0.7 + consistency * this.metrics.avgFps * 0.3) * 10);
let rating = '';
if (score < 200) rating = '⭐ Basic';
else if (score < 400) rating = '⭐⭐ Good';
else if (score < 700) rating = '⭐⭐⭐ Great';
else if (score < 1000) rating = '⭐⭐⭐⭐ Excellent';
else rating = '⭐⭐⭐⭐⭐ Outstanding';
return {
score: score,
rating: rating,
metrics: {
'Avg FPS': this.metrics.avgFps,
'Min FPS': this.metrics.minFps,
'Max FPS': this.metrics.maxFps,
'Frames': this.metrics.totalFrames.toLocaleString()
},
gpu_avg_fps: this.metrics.avgFps,
gpu_min_fps: this.metrics.minFps,
gpu_max_fps: this.metrics.maxFps,
gpu_total_frames: this.metrics.totalFrames
};
}
reset() {
if (this.renderer && this.renderer.reset) {
this.renderer.reset();
}
document.getElementById('fpsCounter').textContent = 'FPS: 0';
document.getElementById('progressBar').style.width = '0%';
}
}
// CPU Benchmark Manager
class CPUBenchmark {
constructor(onComplete) {
this.onComplete = onComplete;
this.workers = [];
this.running = false;
this.startTime = 0;
this.totalDigits = 0;
this.piDigits = '3.';
this.benchmarkDuration = 30000;
this.digitsPerSecond = 0;
this.lastUpdateTime = 0;
this.lastDigitCount = 0;
this.numThreads = navigator.hardwareConcurrency || 4;
}
start() {
this.running = true;
this.startTime = performance.now();
this.lastUpdateTime = this.startTime;
this.lastDigitCount = 0;
this.totalDigits = 0;
this.piDigits = '3.';
document.getElementById('piDigits').textContent = this.piDigits;
document.getElementById('digitCount').textContent = '0';
this.createWorkers();
this.animate();
}
createWorkers() {
const digitsPerWorker = 50000;
for (let i = 0; i < this.numThreads; i++) {
const worker = new Worker('pi-worker.js');
worker.onmessage = (e) => this.handleWorkerMessage(e, i);
worker.onerror = (error) => console.error(`Worker ${i} error:`, error);
this.workers.push(worker);
worker.postMessage({ command: 'start', numDigits: digitsPerWorker });
setTimeout(() => {
if (this.running) {
worker.postMessage({ command: 'stress' });
}
}, 100);
}
}
handleWorkerMessage(e, workerId) {
const { type, digits } = e.data;
if (type === 'digits' && this.running) {
this.addDigits(digits);
this.workers[workerId].postMessage({ command: 'start', numDigits: 1000 });
} else if (type === 'complete') {
if (digits) this.addDigits(digits);
if (this.running) {
this.workers[workerId].postMessage({ command: 'start', numDigits: 50000 });
}
}
}
addDigits(newDigits) {
this.piDigits += newDigits;
this.totalDigits += newDigits.length;
const piDisplay = document.getElementById('piDigits');
const displayDigits = this.piDigits.length > 2000
? '...' + this.piDigits.slice(-2000)
: this.piDigits;
piDisplay.innerHTML = `<span>${displayDigits}</span>`;
piDisplay.scrollTop = piDisplay.scrollHeight;
document.getElementById('digitCount').textContent = this.totalDigits.toLocaleString();
}
animate() {
if (!this.running) return;
const currentTime = performance.now();
const elapsed = currentTime - this.startTime;
const progress = Math.min((elapsed / this.benchmarkDuration) * 100, 100);
document.getElementById('progressBar').style.width = `${progress}%`;
const timeSinceLastUpdate = currentTime - this.lastUpdateTime;
if (timeSinceLastUpdate >= 1000) {
const digitsSinceLastUpdate = this.totalDigits - this.lastDigitCount;
this.digitsPerSecond = Math.round(digitsSinceLastUpdate / (timeSinceLastUpdate / 1000));
this.lastUpdateTime = currentTime;
this.lastDigitCount = this.totalDigits;
}
if (elapsed >= this.benchmarkDuration) {
this.stop();
if (this.onComplete) this.onComplete();
return;
}
requestAnimationFrame(() => this.animate());
}
stop() {
this.running = false;
this.workers.forEach(worker => worker.terminate());
this.workers = [];
}
getResults() {
const elapsedSeconds = (performance.now() - this.startTime) / 1000;
const avgDigitsPerSecond = Math.round(this.totalDigits / elapsedSeconds);
const score = Math.round(avgDigitsPerSecond * (this.numThreads / 4));
let rating = '';
if (score < 5000) rating = '⭐ Basic';
else if (score < 20000) rating = '⭐⭐ Good';
else if (score < 50000) rating = '⭐⭐⭐ Great';
else if (score < 100000) rating = '⭐⭐⭐⭐ Excellent';
else rating = '⭐⭐⭐⭐⭐ Outstanding';
return {
score: score,
rating: rating,
metrics: {
'Digits/Sec': avgDigitsPerSecond.toLocaleString(),
'Total Digits': this.totalDigits.toLocaleString(),
'CPU Threads': this.numThreads,
'Time': `${Math.round(elapsedSeconds)}s`
},
cpu_digits_total: this.totalDigits,
cpu_digits_per_sec: avgDigitsPerSecond,
cpu_threads: this.numThreads
};
}
reset() {
this.stop();
this.piDigits = '3.';
this.totalDigits = 0;
document.getElementById('piDigits').textContent = 'Select CPU test and press Start to begin...';
document.getElementById('digitCount').textContent = '0';
document.getElementById('progressBar').style.width = '0%';
}
}
// Initialize the benchmark controller
const benchmark = new BenchmarkController();