-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbrowser-test.html
More file actions
554 lines (494 loc) · 20.5 KB
/
Copy pathbrowser-test.html
File metadata and controls
554 lines (494 loc) · 20.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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>BLAKE3 vs SHA-256 Browser Benchmark</title>
<script src="coi-serviceworker.min.js"></script>
<style>
body {
font-family: system-ui, sans-serif;
max-width: 1000px;
margin: 0 auto;
padding: 10px 15px;
background: #1a1a2e;
color: #eee;
}
h1 { text-align: center; margin: 8px 0; }
.subtitle { text-align: center; color: #888; margin-bottom: 10px; }
.thread-selector {
text-align: center;
margin-bottom: 8px;
}
.thread-selector label {
color: #888;
font-size: 13px;
margin-right: 6px;
}
.thread-selector select {
background: #252540;
color: #eee;
border: 1px solid #444;
border-radius: 4px;
padding: 4px 8px;
font-size: 13px;
}
.thread-selector select option:disabled { color: #666; }
.file-area {
border: 2px dashed #444;
border-radius: 8px;
padding: 15px 20px;
text-align: center;
margin-bottom: 10px;
cursor: pointer;
}
.file-area:hover { border-color: #666; }
.file-area.dragover { border-color: #4a9eff; background: #1a2a3e; }
.file-area input { display: none; }
.file-area button {
background: #4a9eff;
color: white;
border: none;
padding: 8px 18px;
border-radius: 6px;
font-size: 14px;
cursor: pointer;
margin-top: 4px;
}
.results {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-top: 10px;
}
@media (max-width: 600px) {
.results { grid-template-columns: 1fr; }
}
.result-card {
background: #252540;
border-radius: 8px;
padding: 12px 16px;
}
.result-card h3 {
margin: 0 0 8px 0;
padding-bottom: 6px;
border-bottom: 1px solid #333;
}
.result-card.blake3 h3 { color: #4ade80; }
.result-card.sha256 h3 { color: #a78bfa; }
.stat { margin: 4px 0; }
.stat-label { color: #888; font-size: 14px; }
.stat-value { font-family: monospace; font-size: 14px; word-break: break-all; }
.stat-value.big { font-size: 20px; font-weight: bold; }
.winner { background: #1a3a1a !important; }
.loading { color: #888; }
.file-info {
text-align: center;
margin-top: 15px;
font-size: 18px;
font-weight: bold;
color: #ccc;
}
.benchmark-meta {
text-align: center;
margin-top: 8px;
padding: 6px 12px;
background: #252540;
border-radius: 6px;
font-size: 12px;
color: #aaa;
line-height: 1.6;
}
.benchmark-meta .sep { color: #444; margin: 0 6px; }
.system-info {
background: #252540;
border-radius: 8px;
padding: 8px 14px;
margin-top: 10px;
font-size: 11px;
color: #888;
line-height: 1.4;
}
.system-info summary {
color: #ccc;
font-size: 12px;
font-weight: bold;
cursor: pointer;
}
.system-info span.val { color: #bbb; }
</style>
</head>
<body>
<h1>BLAKE3 vs SHA-256</h1>
<p class="subtitle">Browser Benchmark - Drop a file to compare</p>
<!-- Thread count selector -->
<div class="thread-selector">
<label for="thread-select">Threads:</label>
<select id="thread-select"></select>
</div>
<!-- File input -->
<div class="file-area" id="file-area">
<p style="margin: 4px 0;">Drop a file here</p>
<button type="button">Choose File</button>
<input type="file" id="file-input">
</div>
<!-- Side-by-side results -->
<div class="results" id="results" style="display: none;">
<div id="mode-banner" style="grid-column: 1 / -1; text-align: center; padding: 4px 12px; border-radius: 6px; font-size: 12px; font-weight: bold;"></div>
<div class="result-card blake3" id="blake3-card">
<h3 id="blake3-title">WASM BLAKE3</h3>
<div class="stat">
<div class="stat-value big" id="blake3-speed">-</div>
</div>
<div class="stat">
<div class="stat-value" id="blake3-time">-</div>
</div>
<div class="stat">
<div class="stat-label">Hash</div>
<div class="stat-value" id="blake3-hash">-</div>
</div>
</div>
<div class="result-card sha256" id="sha256-card">
<h3>WebCrypto SHA-256</h3>
<div class="stat">
<div class="stat-value big" id="sha256-speed">-</div>
</div>
<div class="stat">
<div class="stat-value" id="sha256-time">-</div>
</div>
<div class="stat">
<div class="stat-label">Hash</div>
<div class="stat-value" id="sha256-hash">-</div>
</div>
</div>
</div>
<div class="file-info" id="file-info" style="display: none;"></div>
<p id="status" class="loading" style="text-align: center; margin-top: 8px;">
Loading WASM module...
</p>
<!-- Benchmark metadata — always visible after a run -->
<div class="benchmark-meta" id="benchmark-meta" style="display: none;"></div>
<!-- Full system info — collapsible -->
<details class="system-info" id="system-info">
<summary>Full System Info</summary>
<div>Browser: <span class="val" id="info-browser">-</span></div>
<div>Platform: <span class="val" id="info-platform">-</span></div>
<div>CPU Cores: <span class="val" id="info-cores">-</span></div>
<div>BLAKE3 Mode: <span class="val" id="info-mode">loading...</span></div>
<div>Benchmark: <span class="val" id="info-timestamp">-</span></div>
</details>
<script type="module">
// ============================================================
// THREAD COUNT CONFIGURATION
// ============================================================
const cpuCores = navigator.hardwareConcurrency || 4;
const hasSAB = typeof SharedArrayBuffer !== 'undefined';
function getRequestedThreads() {
const params = new URLSearchParams(window.location.hash.slice(1));
const raw = params.get('threads');
if (raw === null || raw === 'auto') return cpuCores;
const val = parseInt(raw, 10);
if (val >= 1 && val <= 16) return val;
return cpuCores;
}
function populateThreadSelector() {
const select = document.getElementById('thread-select');
const requested = getRequestedThreads();
const params = new URLSearchParams(window.location.hash.slice(1));
const isExplicit = params.has('threads') && params.get('threads') !== 'auto';
const options = [
{ value: 'auto', label: `Auto (${cpuCores} cores)` },
{ value: '1', label: '1 thread' },
{ value: '2', label: '2 threads' },
{ value: '3', label: '3 threads' },
{ value: '4', label: '4 threads' },
{ value: '5', label: '5 threads' },
{ value: '6', label: '6 threads' },
{ value: '8', label: '8 threads' },
{ value: '10', label: '10 threads' },
];
for (const opt of options) {
const el = document.createElement('option');
el.value = opt.value;
el.textContent = opt.label;
const numVal = parseInt(opt.value, 10);
if (!hasSAB && numVal > 1) {
el.textContent += ' (unavailable)';
el.disabled = true;
}
if (!isExplicit && opt.value === 'auto') {
el.selected = true;
} else if (isExplicit && numVal === requested) {
el.selected = true;
}
select.appendChild(el);
}
select.addEventListener('change', (e) => {
const val = e.target.value;
if (val === 'auto') {
history.replaceState(null, '', window.location.pathname);
} else {
history.replaceState(null, '', window.location.pathname + '#threads=' + val);
}
window.location.reload();
});
}
// ============================================================
// GLOBAL STATE
// ============================================================
let blake3HashSingle = null; // always loaded
let blake3HashParallel = null; // loaded if SAB available
let isReady = false;
let parallelAvailable = false;
let isAutoMode = false;
let activeThreadCount = 0;
let autoParallelThreads = 0;
const AUTO_THRESHOLD = 10 * 1024 * 1024; // 10 MB
// ============================================================
// INITIALIZATION
// ============================================================
async function init() {
const status = document.getElementById('status');
const blake3Title = document.getElementById('blake3-title');
const modeBanner = document.getElementById('mode-banner');
const params = new URLSearchParams(window.location.hash.slice(1));
const raw = params.get('threads');
isAutoMode = (raw === null || raw === 'auto');
const threadCount = getRequestedThreads();
console.log('[BLAKE3] SharedArrayBuffer:', hasSAB);
console.log('[BLAKE3] crossOriginIsolated:', self.crossOriginIsolated);
console.log('[BLAKE3] Mode:', isAutoMode ? 'auto' : `manual (${threadCount} threads)`);
// --- Step 1: Always load single-threaded build ---
try {
const module = await import('./blake3-wasm-single/pkg/blake3_wasm_single.js');
const wasmResponse = await fetch('./blake3-wasm-single/pkg/blake3_wasm_single_bg.wasm');
const wasmBytes = await wasmResponse.arrayBuffer();
const wasmModule = await WebAssembly.compile(wasmBytes);
await module.default(wasmModule);
blake3HashSingle = (data) => module.hash(data);
console.log('[BLAKE3] Single-threaded build loaded');
} catch (err) {
status.textContent = 'Unable to load BLAKE3 module. Please try refreshing.';
status.style.color = '#f87171';
console.error('[BLAKE3] Single-threaded init failed:', err);
return;
}
// --- Step 2: Try parallel build if applicable ---
const parallelThreads = isAutoMode ? Math.min(3, cpuCores) : threadCount;
if (parallelThreads > 1 && hasSAB) {
try {
const parallelInit = async () => {
const mod = await import('./blake3-wasm-rayon/pkg/blake3_wasm_rayon.js');
const wasmResponse = await fetch('./blake3-wasm-rayon/pkg/blake3_wasm_rayon_bg.wasm');
const wasmBytes = await wasmResponse.arrayBuffer();
const wasmModule = await WebAssembly.compile(wasmBytes);
await mod.default({ module_or_path: wasmModule });
await mod.initThreadPool(parallelThreads);
return mod;
};
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Parallel init timeout (5s)')), 5000)
);
const mod = await Promise.race([parallelInit(), timeout]);
blake3HashParallel = (data) => mod.hash(data);
parallelAvailable = true;
autoParallelThreads = parallelThreads;
console.log(`[BLAKE3] Parallel build loaded (${parallelThreads} threads)`);
} catch (err) {
console.warn('[BLAKE3] Parallel init failed:', err.message);
}
}
// --- Step 3: Set ready state and UI ---
isReady = true;
if (isAutoMode) {
if (parallelAvailable) {
blake3Title.textContent = 'WASM BLAKE3 (auto)';
status.textContent = `Ready! Auto mode \u2014 single (<10 MB) or parallel ${autoParallelThreads} threads (\u226510 MB)`;
status.style.color = '#4ade80';
modeBanner.textContent = `Auto mode \u2014 single + parallel (${autoParallelThreads} threads) available`;
modeBanner.style.background = '#1a3a1a';
modeBanner.style.color = '#4ade80';
document.getElementById('info-mode').textContent =
`Auto (single + parallel ${autoParallelThreads} threads)`;
} else {
blake3Title.textContent = 'WASM BLAKE3 (single-threaded)';
status.textContent = 'Ready! Auto mode \u2014 single-threaded only.';
status.style.color = '#fbbf24';
modeBanner.textContent = 'Auto mode \u2014 single-threaded (WASM SIMD)';
modeBanner.style.background = '#3a2a1a';
modeBanner.style.color = '#fbbf24';
document.getElementById('info-mode').textContent = 'Auto (single-threaded only)';
}
} else if (parallelAvailable && threadCount > 1) {
activeThreadCount = threadCount;
blake3Title.textContent = `WASM BLAKE3 (${threadCount} threads)`;
status.textContent = `Ready! Parallel mode (${threadCount} threads).`;
status.style.color = '#4ade80';
modeBanner.textContent = `Parallel mode \u2014 ${threadCount} threads (SharedArrayBuffer + Web Workers)`;
modeBanner.style.background = '#1a3a1a';
modeBanner.style.color = '#4ade80';
document.getElementById('info-mode').textContent =
`Parallel (${threadCount} threads, SharedArrayBuffer + Web Workers)`;
} else {
activeThreadCount = 1;
blake3Title.textContent = 'WASM BLAKE3 (single-threaded)';
status.textContent = 'Ready! Single-threaded mode.';
status.style.color = '#fbbf24';
modeBanner.textContent = 'Single-threaded mode (WASM SIMD)';
modeBanner.style.background = '#3a2a1a';
modeBanner.style.color = '#fbbf24';
document.getElementById('info-mode').textContent = 'Single-threaded (WASM SIMD)';
}
}
// ============================================================
// HELPERS
// ============================================================
async function hashSha256(data) {
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
return new Uint8Array(hashBuffer);
}
function toHex(bytes) {
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
}
function formatSize(bytes) {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
if (bytes < 1024 * 1024 * 1024) return (bytes / 1024 / 1024).toFixed(1) + ' MB';
return (bytes / 1024 / 1024 / 1024).toFixed(2) + ' GB';
}
function getBrowserShort() {
const ua = navigator.userAgent;
if (ua.includes('Firefox/')) return 'Firefox ' + ua.split('Firefox/')[1].split(' ')[0];
if (ua.includes('Edg/')) return 'Edge ' + ua.split('Edg/')[1].split(' ')[0];
if (ua.includes('Chrome/')) return 'Chrome ' + ua.split('Chrome/')[1].split(' ')[0];
if (ua.includes('Safari/') && !ua.includes('Chrome'))
return 'Safari ' + (ua.split('Version/')[1] || '').split(' ')[0];
return ua.slice(0, 30);
}
function populateSystemInfo() {
document.getElementById('info-browser').textContent = navigator.userAgent;
document.getElementById('info-platform').textContent =
navigator.platform + (navigator.userAgentData ? ' (' + navigator.userAgentData.platform + ')' : '');
document.getElementById('info-cores').textContent =
navigator.hardwareConcurrency ? navigator.hardwareConcurrency + ' logical cores' : 'unknown';
}
// ============================================================
// BENCHMARK
// ============================================================
async function benchmarkFile(file) {
if (!isReady) {
alert('BLAKE3 not ready yet. Please wait.');
return;
}
// Guard: file too large for 64MB WASM memory
if (file.size > 60 * 1024 * 1024) {
const status = document.getElementById('status');
status.textContent = `File too large for WASM (${formatSize(file.size)} > 60 MB limit). Try a smaller file.`;
status.style.color = '#f87171';
return;
}
const results = document.getElementById('results');
const status = document.getElementById('status');
const fileInfo = document.getElementById('file-info');
results.style.display = 'grid';
fileInfo.style.display = 'block';
fileInfo.textContent = `${file.name} \u2014 ${formatSize(file.size)}`;
status.textContent = `Hashing ${file.name} (${formatSize(file.size)})...`;
const now = new Date();
document.getElementById('info-timestamp').textContent = now.toLocaleString();
const arrayBuffer = await file.arrayBuffer();
const data = new Uint8Array(arrayBuffer);
// --- Choose hash function based on mode ---
let hashFn, modeStr;
if (isAutoMode) {
if (file.size >= AUTO_THRESHOLD && parallelAvailable) {
hashFn = blake3HashParallel;
activeThreadCount = autoParallelThreads;
modeStr = `Auto \u2192 parallel ${autoParallelThreads} threads (file \u2265 10 MB)`;
document.getElementById('blake3-title').textContent = `WASM BLAKE3 (${autoParallelThreads} threads)`;
} else {
hashFn = blake3HashSingle;
activeThreadCount = 1;
modeStr = file.size < AUTO_THRESHOLD
? 'Auto \u2192 single-threaded (file < 10 MB)'
: 'Auto \u2192 single-threaded (parallel unavailable)';
document.getElementById('blake3-title').textContent = 'WASM BLAKE3 (single-threaded)';
}
} else {
hashFn = activeThreadCount > 1 && parallelAvailable ? blake3HashParallel : blake3HashSingle;
modeStr = activeThreadCount > 1
? `Parallel (${activeThreadCount} threads)`
: 'Single-threaded (SIMD)';
}
// --- BLAKE3 ---
const blake3Start = performance.now();
const blake3HashResult = hashFn(data);
const blake3Time = performance.now() - blake3Start;
const blake3Speed = (file.size / 1024 / 1024) / (blake3Time / 1000);
document.getElementById('blake3-hash').textContent = toHex(blake3HashResult).slice(0, 16) + '...';
document.getElementById('blake3-time').textContent = blake3Time.toFixed(2) + ' ms';
document.getElementById('blake3-speed').textContent = blake3Speed.toFixed(0) + ' MB/s';
// --- SHA-256 ---
const sha256Start = performance.now();
const sha256HashResult = await hashSha256(data);
const sha256Time = performance.now() - sha256Start;
const sha256Speed = (file.size / 1024 / 1024) / (sha256Time / 1000);
document.getElementById('sha256-hash').textContent = toHex(sha256HashResult).slice(0, 16) + '...';
document.getElementById('sha256-time').textContent = sha256Time.toFixed(2) + ' ms';
document.getElementById('sha256-speed').textContent = sha256Speed.toFixed(0) + ' MB/s';
// Highlight winner
const blake3Card = document.getElementById('blake3-card');
const sha256Card = document.getElementById('sha256-card');
blake3Card.classList.remove('winner');
sha256Card.classList.remove('winner');
if (blake3Speed > sha256Speed) {
blake3Card.classList.add('winner');
const ratio = (blake3Speed / sha256Speed).toFixed(1);
status.textContent = `BLAKE3 wins! ${ratio}x faster than SHA-256`;
status.style.color = '#4ade80';
} else {
sha256Card.classList.add('winner');
const ratio = (sha256Speed / blake3Speed).toFixed(1);
status.textContent = `SHA-256 wins! ${ratio}x faster than BLAKE3`;
status.style.color = '#a78bfa';
}
// Show always-visible metadata bar
const meta = document.getElementById('benchmark-meta');
meta.innerHTML = [
modeStr,
`${cpuCores} cores`,
getBrowserShort(),
now.toLocaleTimeString()
].map(s => `<span>${s}</span>`).join('<span class="sep">|</span>');
meta.style.display = 'block';
}
// ============================================================
// EVENT HANDLERS
// ============================================================
const fileArea = document.getElementById('file-area');
const fileInput = document.getElementById('file-input');
fileArea.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', (e) => {
if (e.target.files[0]) benchmarkFile(e.target.files[0]);
});
fileArea.addEventListener('dragover', (e) => {
e.preventDefault();
fileArea.classList.add('dragover');
});
fileArea.addEventListener('dragleave', () => {
fileArea.classList.remove('dragover');
});
fileArea.addEventListener('drop', (e) => {
e.preventDefault();
fileArea.classList.remove('dragover');
if (e.dataTransfer.files[0]) benchmarkFile(e.dataTransfer.files[0]);
});
// ============================================================
// STARTUP
// ============================================================
populateThreadSelector();
populateSystemInfo();
init();
</script>
</body>
</html>