-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtimer.php
72 lines (55 loc) · 1.8 KB
/
timer.php
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
<?php
// declare strict types for microoptimisations of typing
declare(strict_types=1);
// Enable JIT compilation with optimal settings
ini_set('opcache.jit', 1255); // Tracing JIT
ini_set('opcache.jit_buffer_size', '1024M'); // Increased buffer size for better performance
$start = hrtime(true);
const OUTER_LOOP = 10000;
const INNER_LOOP = 100000;
// Pre-calculate the sum for inner loop - it's always the same!
// For sequence 0 to n-1, sum is (n * (n-1)) / 2
$innerLoopSum = (INNER_LOOP * (INNER_LOOP - 1)) / 2;
// Use SplFixedArray for better memory efficiency
$array = new SplFixedArray(OUTER_LOOP);
// Single loop with mathematical optimization
for ($i = 0; $i < OUTER_LOOP; $i++) {
$array[$i] = $innerLoopSum;
}
$end = hrtime(true);
$difference = ($end - $start) / 1e9;
echo 'Optimised Run: ' . $difference . " seconds\n";
$start = hrtime(true);
$secondArray = array_fill(0, 10000, 0);
for ($i = 0; $i < 10000; $i++) {
for ($j = 0; $j < 100000; $j++) {
$secondArray[$i] += $j;
}
}
$end = hrtime(true);
$differenceTwo = ($end - $start) / 1e9;
echo 'Unoptimised Run: ' . $differenceTwo . " seconds\n";
// Compare results
$areEqual = true;
$firstDifference = null;
$arrayLength = count($secondArray);
for ($i = 0; $i < $arrayLength; $i++) {
if ($secondArray[$i] !== $array[$i]) {
$areEqual = false;
$firstDifference = [
'index' => $i,
'original' => $secondArray[$i],
'optimized' => $array[$i]
];
break;
}
}
// Output results
if ($areEqual) {
echo "Results are strictly equal!\n";
} else {
echo "Results differ at:\n";
echo "Index: " . $firstDifference['index'] . "\n";
echo "Original value: " . $firstDifference['original'] . "\n";
echo "Optimized value: " . $firstDifference['optimized'] . "\n";
}