-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpressPhpBenchmark.php
More file actions
380 lines (289 loc) · 12.4 KB
/
Copy pathExpressPhpBenchmark.php
File metadata and controls
380 lines (289 loc) · 12.4 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
<?php
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
use PivotPHP\Core\Http\Request;
use PivotPHP\Core\Http\Response;
use PivotPHP\Core\Http\Factory\OptimizedHttpFactory;
use PivotPHP\Core\Core\Application;
use PivotPHP\Core\Routing\Router;
/**
* PivotPHP Core - Performance Benchmark
*
* Testa performance do framework com as novas otimizações:
* - Lazy Loading PSR-7
* - Object Pooling
* - Hybrid Request/Response
*/
class ExpressPhpBenchmark
{
private int $iterations;
private array $results = [];
private bool $usePooling = true;
public function __construct(int $iterations = 1000)
{
$this->iterations = $iterations;
// Inicializar factory otimizada
OptimizedHttpFactory::initialize([
'enable_pooling' => $this->usePooling,
'warm_up_pools' => true,
'enable_metrics' => true,
]);
}
public function run(): void
{
echo "🚀 PivotPHP Core - Performance Benchmark\n";
echo "=========================================\n\n";
$this->warmup();
echo "📊 Running benchmarks with {$this->iterations} iterations...\n\n";
// Benchmark 1: Request Creation (Express.js style)
$this->benchmarkRequestCreation();
// Benchmark 2: Response Creation (Express.js style)
$this->benchmarkResponseCreation();
// Benchmark 3: PSR-7 Compatibility
$this->benchmarkPsr7Compatibility();
// Benchmark 4: Hybrid Operations
$this->benchmarkHybridOperations();
// Benchmark 5: Object Pooling Performance
$this->benchmarkObjectPooling();
// Benchmark 6: Route Processing
$this->benchmarkRouteProcessing();
$this->displayResults();
$this->displayPoolingMetrics();
}
private function warmup(): void
{
echo "🔥 Warming up...\n";
// Warm up pools
OptimizedHttpFactory::warmUpPools();
// Warm up JIT
for ($i = 0; $i < 100; $i++) {
$request = new Request('GET', '/test', '/test');
$response = new Response();
$response->json(['test' => true]);
unset($request, $response);
}
echo "✅ Warmup complete\n\n";
}
private function benchmarkRequestCreation(): void
{
echo "📋 Benchmarking Request Creation...\n";
$start = microtime(true);
for ($i = 0; $i < $this->iterations; $i++) {
$request = new Request('GET', '/api/users/' . $i, '/api/users/' . $i);
// Simular uso típico
$request->param('id', $i);
$request->header('Authorization');
$request->ip();
unset($request);
}
$end = microtime(true);
$time = $end - $start;
$this->results['request_creation'] = [
'time' => $time,
'ops_per_sec' => $this->iterations / $time,
'memory_peak' => memory_get_peak_usage(true),
];
echo " ✅ Completed in " . number_format($time, 4) . "s\n";
echo " 📈 " . number_format($this->iterations / $time, 0) . " ops/sec\n\n";
}
private function benchmarkResponseCreation(): void
{
echo "📋 Benchmarking Response Creation...\n";
$start = microtime(true);
for ($i = 0; $i < $this->iterations; $i++) {
$response = new Response();
$response->setTestMode(true); // Evitar output
// Simular uso típico
$response->status(200);
$response->header('Content-Type', 'application/json');
$response->json(['id' => $i, 'name' => "User {$i}"]);
unset($response);
}
$end = microtime(true);
$time = $end - $start;
$this->results['response_creation'] = [
'time' => $time,
'ops_per_sec' => $this->iterations / $time,
'memory_peak' => memory_get_peak_usage(true),
];
echo " ✅ Completed in " . number_format($time, 4) . "s\n";
echo " 📈 " . number_format($this->iterations / $time, 0) . " ops/sec\n\n";
}
private function benchmarkPsr7Compatibility(): void
{
echo "📋 Benchmarking PSR-7 Compatibility...\n";
$start = microtime(true);
for ($i = 0; $i < $this->iterations; $i++) {
$request = new Request('POST', '/api/data', '/api/data');
// Usar métodos PSR-7 (trigger lazy loading)
$request->getMethod();
$request->getUri();
$request->getHeaders();
$request->getBody();
$request->getAttribute('test', 'default');
// Testar imutabilidade
$newRequest = $request->withAttribute('user_id', $i);
$newRequest->getAttribute('user_id');
unset($request, $newRequest);
}
$end = microtime(true);
$time = $end - $start;
$this->results['psr7_compatibility'] = [
'time' => $time,
'ops_per_sec' => $this->iterations / $time,
'memory_peak' => memory_get_peak_usage(true),
];
echo " ✅ Completed in " . number_format($time, 4) . "s\n";
echo " 📈 " . number_format($this->iterations / $time, 0) . " ops/sec\n\n";
}
private function benchmarkHybridOperations(): void
{
echo "📋 Benchmarking Hybrid Operations...\n";
$start = microtime(true);
for ($i = 0; $i < $this->iterations; $i++) {
$request = new Request('GET', '/api/users/:id', '/api/users/' . $i);
$response = new Response();
$response->setTestMode(true);
// Mix Express.js e PSR-7
$userId = $request->param('id'); // Express.js
$headers = $request->getHeaders(); // PSR-7
$response->status(200); // Express.js
$newResponse = $response->withHeader('X-User-ID', (string)$userId); // PSR-7
$newResponse->json(['user' => $userId]); // Express.js
unset($request, $response, $newResponse);
}
$end = microtime(true);
$time = $end - $start;
$this->results['hybrid_operations'] = [
'time' => $time,
'ops_per_sec' => $this->iterations / $time,
'memory_peak' => memory_get_peak_usage(true),
];
echo " ✅ Completed in " . number_format($time, 4) . "s\n";
echo " 📈 " . number_format($this->iterations / $time, 0) . " ops/sec\n\n";
}
private function benchmarkObjectPooling(): void
{
echo "📋 Benchmarking Object Pooling...\n";
// Pré-aquecer pools (não limpar - isso zera as estatísticas)
OptimizedHttpFactory::warmUpPools();
$start = microtime(true);
for ($i = 0; $i < $this->iterations; $i++) {
// Usar factory otimizada
$request = OptimizedHttpFactory::createRequest('GET', '/pool/test', '/pool/test');
$response = OptimizedHttpFactory::createResponse();
// Usar objetos PSR-7 do pool
$psr7Request = OptimizedHttpFactory::createServerRequest('POST', '/psr7/test');
$psr7Response = OptimizedHttpFactory::createPsr7Response(200, [], '{"pooled": true}');
// Retornar objetos ao pool para reutilização
if (method_exists('PivotPHP\Core\Http\Pool\Psr7Pool', 'returnServerRequest')) {
\PivotPHP\Core\Http\Pool\Psr7Pool::returnServerRequest($psr7Request);
\PivotPHP\Core\Http\Pool\Psr7Pool::returnResponse($psr7Response);
}
unset($request, $response, $psr7Request, $psr7Response);
}
$end = microtime(true);
$time = $end - $start;
$this->results['object_pooling'] = [
'time' => $time,
'ops_per_sec' => $this->iterations / $time,
'memory_peak' => memory_get_peak_usage(true),
];
echo " ✅ Completed in " . number_format($time, 4) . "s\n";
echo " 📈 " . number_format($this->iterations / $time, 0) . " ops/sec\n\n";
}
private function benchmarkRouteProcessing(): void
{
echo "📋 Benchmarking Route Processing...\n";
$start = microtime(true);
for ($i = 0; $i < $this->iterations; $i++) {
$request = new Request('GET', '/api/users/:id/posts/:postId', '/api/users/' . $i . '/posts/' . ($i * 10));
// Simular processamento de rota
$userId = $request->param('id');
$postId = $request->param('postId');
$response = new Response();
$response->setTestMode(true);
$response->json([
'user_id' => $userId,
'post_id' => $postId,
'data' => 'Sample data for user ' . $userId
]);
unset($request, $response);
}
$end = microtime(true);
$time = $end - $start;
$this->results['route_processing'] = [
'time' => $time,
'ops_per_sec' => $this->iterations / $time,
'memory_peak' => memory_get_peak_usage(true),
];
echo " ✅ Completed in " . number_format($time, 4) . "s\n";
echo " 📈 " . number_format($this->iterations / $time, 0) . " ops/sec\n\n";
}
private function displayResults(): void
{
echo "📊 BENCHMARK RESULTS\n";
echo "===================\n\n";
$totalOps = 0;
$totalTime = 0;
foreach ($this->results as $name => $result) {
$totalOps += $result['ops_per_sec'];
$totalTime += $result['time'];
echo sprintf("%-20s: %s ops/sec (%.4fs)\n",
ucwords(str_replace('_', ' ', $name)),
number_format($result['ops_per_sec'], 0),
$result['time']
);
}
echo "\n";
echo "📈 Average Performance: " . number_format($totalOps / count($this->results), 0) . " ops/sec\n";
echo "⏱️ Total Time: " . number_format($totalTime, 4) . "s\n";
echo "🧠 Peak Memory: " . $this->formatBytes(memory_get_peak_usage(true)) . "\n";
echo "💾 Current Memory: " . $this->formatBytes(memory_get_usage(true)) . "\n\n";
}
private function displayPoolingMetrics(): void
{
echo "♻️ OBJECT POOLING METRICS\n";
echo "=========================\n\n";
$metrics = OptimizedHttpFactory::getPerformanceMetrics();
if (isset($metrics['metrics_disabled'])) {
echo "⚠️ Pooling metrics disabled\n\n";
return;
}
echo "Pool Efficiency:\n";
foreach ($metrics['pool_efficiency'] as $type => $rate) {
$emoji = $rate > 80 ? '🟢' : ($rate > 50 ? '🟡' : '🔴');
echo sprintf(" %s %-20s: %s %.1f%%\n",
$emoji,
ucwords(str_replace('_', ' ', $type)),
$emoji,
$rate
);
}
echo "\nMemory Usage:\n";
echo sprintf(" Current: %s\n", $this->formatBytes($metrics['memory_usage']['current']));
echo sprintf(" Peak: %s\n", $this->formatBytes($metrics['memory_usage']['peak']));
echo "\nRecommendations:\n";
foreach ($metrics['recommendations'] as $recommendation) {
echo " • {$recommendation}\n";
}
echo "\n";
}
private function formatBytes(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, 2) . ' ' . $units[$pow];
}
}
// Executar benchmark
if (isset($argv[1])) {
$iterations = (int)$argv[1];
} else {
$iterations = 1000;
}
$benchmark = new ExpressPhpBenchmark($iterations);
$benchmark->run();