<?php
/**
 * Comprehensive PHP Benchmark Script
 * Tests various operations to identify performance bottlenecks
 */

header('Content-Type: text/plain');

echo "=== PHP Performance Benchmark ===\n\n";

// System Information
echo "PHP Version: " . PHP_VERSION . "\n";
echo "Server API: " . php_sapi_name() . "\n";
echo "Memory Limit: " . ini_get('memory_limit') . "\n";
echo "Max Execution Time: " . ini_get('max_execution_time') . "s\n";

// Check OPcache
if (function_exists('opcache_get_status')) {
    $opcache = opcache_get_status();
    echo "OPcache Enabled: " . ($opcache ? 'YES' : 'NO') . "\n";
    if ($opcache) {
        echo "OPcache Hit Rate: " . round($opcache['opcache_statistics']['opcache_hit_rate'], 2) . "%\n";
        echo "OPcache Memory Usage: " . round($opcache['memory_usage']['used_memory'] / 1024 / 1024, 2) . " MB\n";
    }
} else {
    echo "OPcache: NOT AVAILABLE\n";
}

echo "\n" . str_repeat("=", 60) . "\n\n";

// Benchmark results array
$results = [];

// Test 1: Integer Operations
$start = microtime(true);
$result = 0;
for ($i = 0; $i < 10000000; $i++) {
    $result += $i * 2;
}
$results['Integer Math (10M ops)'] = microtime(true) - $start;

// Test 2: Float Operations
$start = microtime(true);
$result = 0.0;
for ($i = 0; $i < 5000000; $i++) {
    $result += sqrt($i) * 2.5;
}
$results['Float Math (5M ops)'] = microtime(true) - $start;

// Test 3: String Operations - Concatenation
$start = microtime(true);
$str = '';
for ($i = 0; $i < 100000; $i++) {
    $str .= 'test';
}
$results['String Concat (100K ops)'] = microtime(true) - $start;

// Test 4: String Operations - sprintf
$start = microtime(true);
for ($i = 0; $i < 500000; $i++) {
    $str = sprintf("Value: %d, Name: %s", $i, "test");
}
$results['sprintf (500K ops)'] = microtime(true) - $start;

// Test 5: Array Operations - Push
$start = microtime(true);
$array = [];
for ($i = 0; $i < 100000; $i++) {
    $array[] = $i;
}
$results['Array Push (100K ops)'] = microtime(true) - $start;

// Test 6: Array Operations - Reverse
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
    $reversed = array_reverse($array);
}
$results['Array Reverse (1K ops x 100K items)'] = microtime(true) - $start;

// Test 7: Array Operations - Sort
$test_array = range(1, 10000);
shuffle($test_array);
$start = microtime(true);
for ($i = 0; $i < 100; $i++) {
    $sorted = $test_array;
    sort($sorted);
}
$results['Array Sort (100 ops x 10K items)'] = microtime(true) - $start;

// Test 8: Array Operations - Search
$start = microtime(true);
for ($i = 0; $i < 50000; $i++) {
    $found = in_array(5000, $array);
}
$results['Array Search (50K ops x 100K items)'] = microtime(true) - $start;

// Test 9: Hash Functions
$start = microtime(true);
$data = str_repeat('test', 1000);
for ($i = 0; $i < 10000; $i++) {
    $hash = hash('sha256', $data . $i);
}
$results['SHA256 Hash (10K ops)'] = microtime(true) - $start;

// Test 10: JSON Operations
$json_data = ['name' => 'test', 'value' => 12345, 'data' => range(1, 100)];
$start = microtime(true);
for ($i = 0; $i < 50000; $i++) {
    $encoded = json_encode($json_data);
    $decoded = json_decode($encoded, true);
}
$results['JSON encode/decode (50K ops)'] = microtime(true) - $start;

// Test 11: Regular Expressions
$pattern = '/^[a-z0-9_-]{3,16}$/';
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    $match = preg_match($pattern, 'test_user_' . $i);
}
$results['Regex Match (100K ops)'] = microtime(true) - $start;

// Test 12: File Operations - Write
$filename = 'benchmark_test.txt';
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
    file_put_contents($filename, "Line $i\n", FILE_APPEND);
}
$results['File Write (1K ops)'] = microtime(true) - $start;

// Test 13: File Operations - Read
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
    $content = file_get_contents($filename);
}
$results['File Read (1K ops)'] = microtime(true) - $start;
@unlink($filename);

// Test 14: Memory Allocation
$start = microtime(true);
$memory_arrays = [];
for ($i = 0; $i < 1000; $i++) {
    $memory_arrays[] = range(1, 1000);
}
unset($memory_arrays);
$results['Memory Allocation (1K arrays x 1K items)'] = microtime(true) - $start;

// Test 15: Function Calls
function test_function($a, $b, $c) {
    return $a + $b + $c;
}
$start = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
    $result = test_function(1, 2, 3);
}
$results['Function Calls (1M ops)'] = microtime(true) - $start;

// Test 16: Object Creation
class TestClass {
    public $prop1 = 1;
    public $prop2 = 'test';
    public function method() {
        return $this->prop1 + strlen($this->prop2);
    }
}
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    $obj = new TestClass();
    $result = $obj->method();
}
$results['Object Creation & Method Call (100K ops)'] = microtime(true) - $start;

// Calculate total time
$total_time = array_sum($results);

// Display Results
echo "Benchmark Results:\n";
echo str_repeat("-", 60) . "\n";

foreach ($results as $test => $time) {
    $percentage = ($time / $total_time) * 100;
    printf("%-45s: %7.4fs (%5.1f%%)\n", $test, $time, $percentage);
}

echo str_repeat("-", 60) . "\n";
printf("%-45s: %7.4fs\n", "TOTAL TIME", $total_time);

// Performance Score (lower is better)
$baseline_time = 5.0; // Baseline reference time
$performance_score = ($baseline_time / $total_time) * 100;
echo "\nPerformance Score: " . round($performance_score, 2) . " (100 = baseline)\n";

// Memory Usage
echo "\nMemory Usage:\n";
echo "Peak Memory: " . round(memory_get_peak_usage(true) / 1024 / 1024, 2) . " MB\n";
echo "Current Memory: " . round(memory_get_usage(true) / 1024 / 1024, 2) . " MB\n";

// Save results to file
$results_file = 'benchmark_results_' . date('Y-m-d_H-i-s') . '.txt';
ob_start();
echo "=== PHP Benchmark Results ===\n";
echo "Date: " . date('Y-m-d H:i:s') . "\n";
echo "PHP Version: " . PHP_VERSION . "\n";
echo "Server API: " . php_sapi_name() . "\n\n";
foreach ($results as $test => $time) {
    printf("%-45s: %7.4fs\n", $test, $time);
}
printf("\nTotal Time: %.4fs\n", $total_time);
printf("Performance Score: %.2f\n", $performance_score);
$output = ob_get_clean();
file_put_contents($results_file, $output);

echo "\nResults saved to: $results_file\n";

?>