-
Notifications
You must be signed in to change notification settings - Fork 592
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
experiment: explore benchmarking with playwright #4776
Closed
+6,322
−211
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
import React, {Profiler} from 'react' | ||
import {createRoot, type Root} from 'react-dom/client' | ||
import {Button} from '../Button' | ||
import BaseStyles from '../BaseStyles' | ||
import ThemeProvider from '../ThemeProvider' | ||
|
||
declare global { | ||
interface Window { | ||
BenchmarkRunner: BenchmarkRunner | ||
} | ||
} | ||
|
||
interface BenchmarkRunner { | ||
addBenchmark(benchmark: Benchmark): void | ||
runBenchmarks(): Promise< | ||
Array<{ | ||
benchmark: Benchmark | ||
result: BenchmarkResult | ||
}> | ||
> | ||
} | ||
|
||
class BenchmarkRunner implements BenchmarkRunner { | ||
benchmarks: Array<Benchmark> = [] | ||
|
||
addBenchmark(benchmark: Benchmark): void { | ||
this.benchmarks.push(benchmark) | ||
} | ||
|
||
async runBenchmarks(): Promise< | ||
Array<{ | ||
benchmark: Benchmark | ||
result: BenchmarkResult | ||
}> | ||
> { | ||
const results = [] | ||
|
||
for (const benchmark of this.benchmarks) { | ||
const runs: Array<BenchmarkRunResult> = [] | ||
|
||
for (let i = 0; i < 1000; i++) { | ||
await benchmark.setup() | ||
|
||
const run = await benchmark.run() | ||
runs.push(run) | ||
|
||
await benchmark.teardown() | ||
} | ||
|
||
const result: BenchmarkResult = { | ||
averageBaseDuration: average(runs, 'baseDuration'), | ||
averageActualDuration: average(runs, 'actualDuration'), | ||
medianBaseDuration: median(runs, 'baseDuration'), | ||
medianActualDuration: median(runs, 'actualDuration'), | ||
runs, | ||
} | ||
|
||
results.push({ | ||
benchmark, | ||
result, | ||
}) | ||
} | ||
|
||
return results | ||
} | ||
} | ||
|
||
function average<K extends string, T extends Record<K, number>>(series: Array<T>, field: K): number { | ||
let sum = 0 | ||
|
||
for (const value of series) { | ||
sum += value[field] | ||
} | ||
|
||
return sum / series.length | ||
} | ||
|
||
function median<K extends string, T extends Record<K, number>>(series: Array<T>, field: K): number { | ||
const values: Array<number> = series.map(value => value[field]).sort() | ||
return values[Math.floor(values.length / 2)] | ||
} | ||
|
||
interface Benchmark { | ||
name: string | ||
setup(): Promise<void> | void | ||
run(): Promise<BenchmarkRunResult> | ||
teardown(): Promise<void> | void | ||
} | ||
|
||
interface BenchmarkResult { | ||
averageActualDuration: number | ||
averageBaseDuration: number | ||
medianActualDuration: number | ||
medianBaseDuration: number | ||
runs: Array<BenchmarkRunResult> | ||
} | ||
|
||
interface BenchmarkRunResult { | ||
phase: 'update' | 'mount' | 'nested-update' | ||
actualDuration: number | ||
baseDuration: number | ||
} | ||
|
||
window.BenchmarkRunner = new BenchmarkRunner() | ||
|
||
benchmark('Button', ({render, onRender}) => { | ||
render( | ||
<ThemeProvider> | ||
<BaseStyles> | ||
<Profiler id="benchmark" onRender={onRender}> | ||
<Button>Test case</Button> | ||
</Profiler> | ||
</BaseStyles> | ||
</ThemeProvider>, | ||
) | ||
}) | ||
|
||
function benchmark( | ||
name: string, | ||
fn: ({render, onRender}: {render: (element: JSX.Element) => void; onRender: React.ProfilerProps['onRender']}) => void, | ||
) { | ||
let root: Root | null = null | ||
|
||
function setup() { | ||
const node = document.createElement('div') | ||
node.setAttribute('id', 'benchmark') | ||
document.body.appendChild(node) | ||
root = createRoot(node) | ||
} | ||
|
||
function teardown() { | ||
root?.unmount() | ||
const node = document.getElementById('benchmark') | ||
if (node) { | ||
node.remove() | ||
} | ||
root = null | ||
} | ||
|
||
function run(): Promise<BenchmarkRunResult> { | ||
return new Promise(resolve => { | ||
const onRender: React.ProfilerProps['onRender'] = (_id, phase, actualDuration, baseDuration) => { | ||
resolve({ | ||
phase, | ||
actualDuration, | ||
baseDuration, | ||
}) | ||
} | ||
const render = (element: JSX.Element) => { | ||
root?.render(element) | ||
} | ||
fn({ | ||
render, | ||
onRender, | ||
}) | ||
}) | ||
} | ||
|
||
const benchmark: Benchmark = { | ||
name, | ||
setup, | ||
teardown, | ||
run, | ||
} | ||
|
||
window.BenchmarkRunner.addBenchmark(benchmark) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,193 @@ | ||
import {chromium, devices} from 'playwright' | ||
import process from 'node:process' | ||
import path from 'node:path' | ||
import glob from 'fast-glob' | ||
import * as esbuild from 'esbuild' | ||
import {createServer, request, type Server} from 'node:http' | ||
import {parse} from 'node:url' | ||
import {existsSync, createReadStream} from 'node:fs' | ||
|
||
async function benchmarks() { | ||
const cwd = process.cwd() | ||
const files = await glob('**/*.benchmarks.tsx', { | ||
cwd, | ||
ignore: ['**/node_modules/**', '**/dist/**', '**/lib/**', '**/lib-esm/**'], | ||
}) | ||
|
||
await esbuild.build({ | ||
bundle: true, | ||
platform: 'browser', | ||
entryPoints: files, | ||
tsconfig: path.join(cwd, 'packages', 'react', 'tsconfig.build.json'), | ||
outdir: 'assets', | ||
outbase: cwd, | ||
minify: true, | ||
define: { | ||
__DEV__: 'false', | ||
}, | ||
alias: { | ||
'react-dom/client': 'react-dom/profiling', | ||
}, | ||
}) | ||
|
||
const server = createServer(async (req, res) => { | ||
try { | ||
console.log('debug: %s %s', req.method, req.url) | ||
if (!req.url) { | ||
throw new Error('Invalid URL') | ||
} | ||
|
||
const url = parse(req.url, true) | ||
if (!url.path) { | ||
throw new Error('Invalid path in URL for requested asset') | ||
} | ||
|
||
if (req.url?.startsWith('/assets')) { | ||
const filepath = path.join(cwd, url.path) | ||
if (!existsSync(filepath)) { | ||
res.statusCode = 404 | ||
res.end('not found') | ||
return | ||
} | ||
|
||
res.writeHead(200, { | ||
'Content-Type': 'application/javascript', | ||
}) | ||
createReadStream(filepath).pipe(res, {end: true}) | ||
Check failure Code scanning / CodeQL Uncontrolled data used in path expression High
This path depends on a
user-provided value Error loading related location Loading |
||
} else if (req.url?.startsWith('/benchmarks')) { | ||
const benchmarkPath = path.parse(url.path.split('/').slice(2).join(path.sep)) | ||
const assetPath = path.format({ | ||
...benchmarkPath, | ||
base: '', | ||
ext: '.js', | ||
}) | ||
|
||
res.writeHead(200, { | ||
'Content-Type': 'text-html', | ||
}) | ||
res.end(` | ||
<!DOCTYPE html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="UTF-8"> | ||
<title>Benchmark</title> | ||
</head> | ||
<body> | ||
<div id="root"></div> | ||
<script src="/assets/${assetPath}"></script> | ||
</body> | ||
</html> | ||
`) | ||
} else { | ||
res.statusCode = 404 | ||
res.end('not found') | ||
} | ||
} catch (error) { | ||
console.error('Error occurred handling', req.url, error) | ||
res.statusCode = 500 | ||
res.end('internal server error') | ||
} | ||
|
||
// try { | ||
// if (req.method !== 'GET') { | ||
// res.statusCode = 405 | ||
// res.end('method not allowed') | ||
// return | ||
// } | ||
|
||
// if (req.url?.startsWith('/benchmarks')) { | ||
// console.log('debug: GET %s', req.url) | ||
|
||
// const url = parse(req.url, true) | ||
// if (!url.path) { | ||
// throw new Error('Invalid path in URL for requested benchmark') | ||
// } | ||
|
||
// const requestedBenchmarkPath = url.path.split('/').slice(2).join(path.sep) | ||
// const filepath = path.join(cwd, requestedBenchmarkPath) | ||
// console.log(filepath) | ||
// if (!existsSync(filepath)) { | ||
// res.statusCode = 404 | ||
// res.end('not found') | ||
// return | ||
// } | ||
|
||
// console.log(filepath) | ||
|
||
// res.writeHead(200, { | ||
// 'Content-Type': 'text/html', | ||
// }) | ||
// res.end(` | ||
// <!DOCTYPE html> | ||
// <html lang="en"> | ||
// <head> | ||
// <meta charset="UTF-8"> | ||
// <title>Benchmark</title> | ||
// </head> | ||
// <body> | ||
// <h1>Hello world</h1> | ||
// </body> | ||
// </html> | ||
// `) | ||
// return | ||
// } | ||
|
||
// res.statusCode = 404 | ||
// res.end('not found') | ||
// } catch (err) { | ||
// console.error('Error occurred handling', req.url, err) | ||
// res.statusCode = 500 | ||
// res.end('internal server error') | ||
// } | ||
}) | ||
|
||
server.once('error', err => { | ||
console.error(err) | ||
process.exit(1) | ||
}) | ||
|
||
await listen(server, 3000, '0.0.0.0') | ||
console.log('debug: server running on', `http://0.0.0.0:3000`) | ||
|
||
// Setup | ||
const browser = await chromium.launch() | ||
const context = await browser.newContext(devices['Desktop Chrome']) | ||
|
||
for (const file of files) { | ||
const page = await context.newPage() | ||
const url = new URL(`/benchmarks/${file}`, 'http://0.0.0.0:3000') | ||
await page.goto(url.toString()) | ||
|
||
const results = await page.evaluate(() => { | ||
return window.BenchmarkRunner.runBenchmarks() | ||
}) | ||
console.log(results[0].result.runs) | ||
|
||
await page.close() | ||
} | ||
|
||
await context.close() | ||
await browser.close() | ||
await close(server) | ||
} | ||
|
||
function close(server: Server): Promise<void> { | ||
return new Promise(resolve => { | ||
server.close(() => { | ||
resolve() | ||
}) | ||
}) | ||
} | ||
|
||
function listen(server: Server, port: number, hostname: string): Promise<void> { | ||
return new Promise(resolve => { | ||
server.listen(port, hostname, () => { | ||
resolve() | ||
}) | ||
}) | ||
} | ||
|
||
benchmarks().catch(error => { | ||
console.log(error) | ||
process.exit(1) | ||
}) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / CodeQL
Uncontrolled data used in path expression High