Files
michaelschiemer/examples/memory-profiling-usage.php
Michael Schiemer fc3d7e6357 feat(Production): Complete production deployment infrastructure
- Add comprehensive health check system with multiple endpoints
- Add Prometheus metrics endpoint
- Add production logging configurations (5 strategies)
- Add complete deployment documentation suite:
  * QUICKSTART.md - 30-minute deployment guide
  * DEPLOYMENT_CHECKLIST.md - Printable verification checklist
  * DEPLOYMENT_WORKFLOW.md - Complete deployment lifecycle
  * PRODUCTION_DEPLOYMENT.md - Comprehensive technical reference
  * production-logging.md - Logging configuration guide
  * ANSIBLE_DEPLOYMENT.md - Infrastructure as Code automation
  * README.md - Navigation hub
  * DEPLOYMENT_SUMMARY.md - Executive summary
- Add deployment scripts and automation
- Add DEPLOYMENT_PLAN.md - Concrete plan for immediate deployment
- Update README with production-ready features

All production infrastructure is now complete and ready for deployment.
2025-10-25 19:18:37 +02:00

415 lines
13 KiB
PHP
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
/**
* Memory Profiling Usage Examples
*
* Dieses Script demonstriert die erweiterten Memory-Profiling-Funktionen
* mit dem MemoryProfiler für detaillierte Memory-Analyse.
*
* Ausführung: php examples/memory-profiling-usage.php
*/
require_once __DIR__ . '/../vendor/autoload.php';
use App\Framework\Performance\NestedPerformanceTracker;
use App\Framework\Performance\MemoryProfiler;
use App\Framework\Performance\PerformanceCategory;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Performance\MemoryMonitor;
// Initialize tracker and profiler
$tracker = new NestedPerformanceTracker(
new SystemClock(),
new SystemHighResolutionClock(),
new MemoryMonitor()
);
$profiler = new MemoryProfiler($tracker);
echo "=== Memory Profiling Examples ===\n\n";
// Example 1: Memory Hotspot Identification
echo "Example 1: Memory Hotspot Identification\n";
echo str_repeat('-', 50) . "\n";
// Simuliere verschiedene Operations mit unterschiedlichem Memory-Verbrauch
$tracker->measure(
'database.query.large_result',
PerformanceCategory::DATABASE,
function () {
// Simuliere große Datenbank-Abfrage
$data = array_fill(0, 10000, str_repeat('x', 100)); // ~1MB
usleep(5000); // 5ms
}
);
$tracker->measure(
'cache.load',
PerformanceCategory::CACHE,
function () {
// Simuliere Cache-Load
$data = array_fill(0, 1000, str_repeat('x', 100)); // ~0.1MB
usleep(1000); // 1ms
}
);
$tracker->measure(
'api.process',
PerformanceCategory::API,
function () {
// Simuliere API Processing
$data = array_fill(0, 5000, str_repeat('x', 100)); // ~0.5MB
usleep(3000); // 3ms
}
);
echo "\nMemory Hotspots (Top 5):\n";
$hotspots = $profiler->getMemoryHotspots(5);
foreach ($hotspots as $index => $hotspot) {
echo sprintf(
" %d. %s [%s]\n" .
" Memory: %.2fMB | Duration: %.2fms | Memory/ms: %.4fMB\n",
$index + 1,
$hotspot['operation'],
$hotspot['category'],
$hotspot['memory_mb'],
$hotspot['duration_ms'],
$hotspot['memory_per_ms']
);
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 2: Memory Leak Detection
echo "Example 2: Memory Leak Detection\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere potentielle Memory Leaks
for ($i = 0; $i < 5; $i++) {
$tracker->measure(
"iteration.{$i}",
PerformanceCategory::CUSTOM,
function () use ($i) {
// Simuliere steigendes Memory (Leak Pattern)
$data = array_fill(0, ($i + 1) * 2000, str_repeat('x', 100));
usleep(2000);
}
);
}
$leakDetection = $profiler->detectMemoryLeaks(0.5); // 0.5MB threshold
echo "\nMemory Leak Detection Results:\n";
echo " Threshold: {$leakDetection['threshold_mb']}MB\n";
echo " Potential Leaks Found: {$leakDetection['leak_count']}\n";
echo " Total Memory Growth: {$leakDetection['total_memory_growth_mb']}MB\n\n";
if (!empty($leakDetection['potential_leaks'])) {
echo " Detected Leaks:\n";
foreach ($leakDetection['potential_leaks'] as $leak) {
echo sprintf(
" • %s: %.2fMB allocated (Cumulative: %.2fMB)\n",
$leak['operation'],
$leak['memory_allocated_mb'],
$leak['cumulative_memory_mb']
);
}
} else {
echo " ✅ No memory leaks detected\n";
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 3: Memory Efficiency Scoring
echo "Example 3: Memory Efficiency Scoring\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere effiziente vs. ineffiziente Operations
$tracker->measure(
'efficient.operation',
PerformanceCategory::CUSTOM,
function () {
$data = array_fill(0, 100, str_repeat('x', 10)); // Small memory
usleep(1000); // 1ms
}
);
$tracker->measure(
'inefficient.operation',
PerformanceCategory::CUSTOM,
function () {
$data = array_fill(0, 10000, str_repeat('x', 100)); // Large memory
usleep(1000); // 1ms (same time, more memory)
}
);
$efficiency = $profiler->calculateEfficiencyScore();
echo "\nMemory Efficiency Score:\n";
echo " Score: {$efficiency['score']}/100\n";
echo " Rating: {$efficiency['rating']}\n";
echo " Total Memory: {$efficiency['total_memory_mb']}MB\n";
echo " Total Time: {$efficiency['total_time_ms']}ms\n";
echo " Memory per ms: {$efficiency['memory_per_ms']}MB\n";
$ratingColor = match ($efficiency['rating']) {
'Excellent' => '✅',
'Good' => '👍',
'Fair' => '⚠️',
'Poor' => '❌',
'Critical' => '🚨',
default => ''
};
echo "\n {$ratingColor} {$efficiency['rating']} - ";
echo match ($efficiency['rating']) {
'Excellent' => "Sehr geringe Memory-Nutzung",
'Good' => "Akzeptable Memory-Nutzung",
'Fair' => "Durchschnittliche Memory-Nutzung",
'Poor' => "Hohe Memory-Nutzung - Optimierung empfohlen",
'Critical' => "Kritische Memory-Nutzung - Sofortige Optimierung erforderlich",
default => "Keine Daten verfügbar"
};
echo "\n";
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 4: Comprehensive Memory Report
echo "Example 4: Comprehensive Memory Report\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere gemischte Operations
$categories = [
['category' => PerformanceCategory::DATABASE, 'count' => 3],
['category' => PerformanceCategory::CACHE, 'count' => 2],
['category' => PerformanceCategory::API, 'count' => 4],
['category' => PerformanceCategory::TEMPLATE, 'count' => 1]
];
foreach ($categories as $categoryConfig) {
$category = $categoryConfig['category'];
$count = $categoryConfig['count'];
for ($i = 0; $i < $count; $i++) {
$tracker->measure(
"{$category->value}_operation_{$i}",
$category,
function () use ($i) {
$size = rand(100, 5000);
$data = array_fill(0, $size, str_repeat('x', 10));
usleep(rand(500, 2000));
}
);
}
}
$report = $profiler->generateMemoryReport();
echo "\nMemory Report Summary:\n";
echo " Total Operations: {$report['summary']['total_operations']}\n";
echo " Total Memory: {$report['summary']['total_memory_mb']}MB\n";
echo " Avg Memory per Operation: {$report['summary']['avg_memory_per_operation_mb']}MB\n";
echo " Peak Memory: {$report['summary']['peak_memory_mb']}MB\n\n";
echo " Memory by Category:\n";
foreach ($report['by_category'] as $category => $data) {
echo sprintf(
" • %s: %.2fMB total (%.4fMB avg, %.2fMB peak, %d ops)\n",
$category,
$data['total_memory_mb'],
$data['avg_memory_mb'],
$data['peak_memory_mb'],
$data['operations']
);
}
echo "\n Top Memory Hotspots:\n";
foreach ($report['hotspots'] as $index => $hotspot) {
echo sprintf(
" %d. %s: %.2fMB\n",
$index + 1,
$hotspot['operation'],
$hotspot['memory_mb']
);
}
echo "\n Efficiency: {$report['efficiency']['score']}/100 ({$report['efficiency']['rating']})\n";
echo " Leak Detection: {$report['leaks']['leak_count']} potential leaks\n";
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 5: Memory Over Time Tracking
echo "Example 5: Memory Over Time Tracking\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere wachsende Memory-Nutzung über Zeit
for ($i = 0; $i < 10; $i++) {
$tracker->measure(
"timestep_{$i}",
PerformanceCategory::CUSTOM,
function () use ($i) {
// Memory wächst über Zeit
$size = ($i + 1) * 500;
$data = array_fill(0, $size, str_repeat('x', 10));
usleep(1000);
}
);
}
$memoryTracking = $profiler->trackMemoryOverTime();
echo "\nMemory Tracking Over Time:\n";
echo " Final Cumulative Memory: {$memoryTracking['final_cumulative_mb']}MB\n";
echo " Trend: {$memoryTracking['trend']}\n\n";
echo " Timeline (first 5 points):\n";
foreach (array_slice($memoryTracking['tracking_points'], 0, 5) as $point) {
echo sprintf(
" • %s: +%.2fMB (Cumulative: %.2fMB)\n",
$point['operation'],
$point['delta_mb'],
$point['cumulative_mb']
);
}
echo "\n 💡 Trend Analysis:\n";
echo " " . match ($memoryTracking['trend']) {
'rapidly_growing' => "⚠️ Memory wächst schnell - Leak-Überprüfung empfohlen",
'growing' => "⚠️ Memory wächst - Monitoring fortsetzen",
'stable' => "✅ Stabiler Memory-Verbrauch",
'decreasing' => "✅ Memory-Nutzung nimmt ab",
'rapidly_decreasing' => "✅ Memory wird schnell freigegeben",
default => " Unzureichende Daten für Trend-Analyse"
};
echo "\n";
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 6: Memory Budget Validation
echo "Example 6: Memory Budget Validation\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere Operations mit Memory-Budgets
$tracker->measure('api.request', PerformanceCategory::API, function () {
$data = array_fill(0, 3000, str_repeat('x', 100)); // ~0.3MB
usleep(2000);
});
$tracker->measure('database.query', PerformanceCategory::DATABASE, function () {
$data = array_fill(0, 15000, str_repeat('x', 100)); // ~1.5MB
usleep(5000);
});
$tracker->measure('cache.get', PerformanceCategory::CACHE, function () {
$data = array_fill(0, 500, str_repeat('x', 100)); // ~0.05MB
usleep(500);
});
// Define memory budgets
$budgets = [
'api.request' => 0.5, // max 0.5MB
'database.query' => 1.0, // max 1MB
'cache.get' => 0.1, // max 0.1MB
];
$budgetViolations = $profiler->getMemoryBudgetViolations($budgets);
echo "\nMemory Budget Validation:\n";
echo " Budgets Checked: {$budgetViolations['budgets_checked']}\n";
echo " Violations Found: {$budgetViolations['violation_count']}\n\n";
if (!empty($budgetViolations['violations'])) {
echo " ⚠️ Budget Violations:\n";
foreach ($budgetViolations['violations'] as $violation) {
echo sprintf(
" • %s: %.2fMB (Budget: %.2fMB, Exceeded by: %.2fMB / %.1f%%)\n",
$violation['operation'],
$violation['memory_mb'],
$violation['budget_mb'],
$violation['exceeded_by_mb'],
$violation['percentage']
);
}
} else {
echo " ✅ All operations within memory budget!\n";
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 7: Operation Comparison
echo "Example 7: Memory Usage Comparison (A/B Testing)\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere zwei verschiedene Implementierungen
$tracker->measure('implementation.v1', PerformanceCategory::CUSTOM, function () {
$data = array_fill(0, 10000, str_repeat('x', 100)); // ~1MB
usleep(3000);
});
$tracker->measure('implementation.v2', PerformanceCategory::CUSTOM, function () {
$data = array_fill(0, 5000, str_repeat('x', 100)); // ~0.5MB (optimized)
usleep(3000);
});
$comparison = $profiler->compareOperations('implementation.v1', 'implementation.v2');
echo "\nA/B Comparison Results:\n\n";
echo " Implementation v1:\n";
echo " Memory: {$comparison['operation_1']['memory_mb']}MB\n";
echo " Executions: {$comparison['operation_1']['executions']}\n\n";
echo " Implementation v2:\n";
echo " Memory: {$comparison['operation_2']['memory_mb']}MB\n";
echo " Executions: {$comparison['operation_2']['executions']}\n\n";
echo " Comparison:\n";
echo " Difference: {$comparison['comparison']['difference_mb']}MB\n";
echo " Percentage Diff: {$comparison['comparison']['percentage_diff']}%\n";
echo " Winner: {$comparison['comparison']['winner']}\n";
$savings = abs($comparison['comparison']['percentage_diff']);
if ($savings > 0) {
echo "\n 💡 v2 uses {$savings}% less memory than v1\n";
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Summary
echo "✅ Memory Profiling Examples completed!\n\n";
echo "Key Insights:\n";
echo " • MemoryProfiler provides comprehensive memory analysis\n";
echo " • Memory leak detection helps identify growing allocations\n";
echo " • Efficiency scoring rates memory usage vs. execution time\n";
echo " • Memory budgets ensure operations stay within limits\n";
echo " • A/B testing helps validate memory optimizations\n\n";
echo "Use Cases:\n";
echo " 1. Identify memory hotspots for optimization\n";
echo " 2. Detect and prevent memory leaks\n";
echo " 3. Monitor memory efficiency over time\n";
echo " 4. Validate memory budgets in production\n";
echo " 5. Compare memory usage between implementations\n\n";
echo "Next Steps:\n";
echo " 1. Set memory budgets for critical operations\n";
echo " 2. Monitor memory trends in production\n";
echo " 3. Alert on memory efficiency degradation\n";
echo " 4. Use A/B testing for memory optimizations\n\n";