-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtest_performance.php
More file actions
67 lines (58 loc) · 1.79 KB
/
test_performance.php
File metadata and controls
67 lines (58 loc) · 1.79 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
<?php
/**
* Generates 10 million numbers using yield (Generator).
*/
function generatorFunction(int $count): Generator
{
for ($i = 0; $i < $count; $i++) {
yield $i;
}
}
/**
* Generates 10 million numbers using an array (Traditional Loop).
*/
function loopFunction(int $count): array
{
$numbers = [];
for ($i = 0; $i < $count; $i++) {
$numbers[] = $i;
}
return $numbers;
}
// Define dataset size
$size = 10000000;
// Test Generator (yield)
$startTime = microtime(true);
$startMemory = memory_get_usage();
$total_gen_iteration = 0;
foreach (generatorFunction($size) as $num) {
// Just iterating
$total_gen_iteration++;
}
$endMemory = memory_get_usage();
$endTime = microtime(true);
$generatorTime = $endTime - $startTime;
$generatorMemory = memory_get_peak_usage() - $startMemory;
// Test Traditional Loop (Array)
$startTime = microtime(true);
$startMemory = memory_get_usage();
$numbers = loopFunction($size);
$total_loop_iteration = 0;
foreach ($numbers as $num) {
// Just iterating
$total_loop_iteration++;
}
$endMemory = memory_get_usage();
$endTime = microtime(true);
$loopTime = $endTime - $startTime;
$loopMemory = memory_get_peak_usage() - $startMemory;
// Display Results
echo "Performance Comparison for 10 Million Data Points\n";
echo "------------------------------------------------\n";
echo "Using Generator (yield): $total_gen_iteration \n";
echo 'Execution Time: '.number_format($generatorTime, 4)." sec\n";
echo 'Memory Usage: '.number_format($generatorMemory / (1024 * 1024), 4)." MB\n";
echo "------------------------------------------------\n";
echo "Using Traditional Loop (Array): $total_loop_iteration \n";
echo 'Execution Time: '.number_format($loopTime, 4)." sec\n";
echo 'Memory Usage: '.number_format($loopMemory / (1024 * 1024), 4)." MB\n";