1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of library-template |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
* |
8
|
|
|
* @author Nicolò Martini <[email protected]> |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* This is a basic benchmark test for Engine... |
13
|
|
|
*/ |
14
|
|
|
include '../vendor/autoload.php'; |
15
|
|
|
|
16
|
|
|
$engine = new \StringTemplate\Engine; |
17
|
|
|
$template = "These are {foo} and {bar}. Those are {goo.b} and {goo.v} %"; |
18
|
|
|
$vars = array( |
19
|
|
|
'foo' => 'bar', |
20
|
|
|
'baz' => 'friend', |
21
|
|
|
'goo' => array('a' => 'b', 'c' => 'd') |
22
|
|
|
); |
23
|
|
|
$replace = function () use ($engine, $template, $vars) |
24
|
|
|
{ |
25
|
|
|
$engine->render($template, $vars); |
26
|
|
|
}; |
27
|
|
|
|
28
|
|
|
$engineSprintf = new \StringTemplate\SprintfEngine; |
29
|
|
|
$replaceSprintf = function () use ($engineSprintf, $template, $vars) { |
30
|
|
|
$engineSprintf->render($template, $vars); |
31
|
|
|
}; |
32
|
|
|
|
33
|
|
|
$templateSprintf = "These are %s and %s. Those are %s and %s"; |
34
|
|
|
$varsSprintf = array( |
35
|
|
|
'bar', 'friend', 'b', 'd' |
36
|
|
|
); |
37
|
|
|
$sprintf = function () use ($template, $varsSprintf) |
38
|
|
|
{ |
39
|
|
|
$args = array_merge(array($template), $varsSprintf); |
40
|
|
|
call_user_func_array('sprintf', $args); |
41
|
|
|
}; |
42
|
|
|
|
43
|
|
|
$varsSearch = array( |
44
|
|
|
'foo', 'baz', 'goo.a', 'goo.c' |
45
|
|
|
); |
46
|
|
|
$varsReplace = array( |
47
|
|
|
'bar', 'friend', 'b', 'd' |
48
|
|
|
); |
49
|
|
|
|
50
|
|
|
$strReplace = function () use ($template, $varsSearch, $varsReplace) |
51
|
|
|
{ |
52
|
|
|
str_replace($varsSearch, $varsReplace, $template); |
53
|
|
|
}; |
54
|
|
|
|
55
|
|
|
function benchmark($f, $title = '', $iterations = 100000) |
56
|
|
|
{ |
57
|
|
|
static $firstTime = 0; |
58
|
|
|
echo '<br><b>', $title, '</b><br>'; |
59
|
|
|
$start = microtime(true); |
60
|
|
|
for ($i = 0; $i < $iterations; $i++) |
61
|
|
|
$f(); |
62
|
|
|
$time = microtime(true) - $start; |
63
|
|
|
echo 'Time: ', $time, '<br>'; |
64
|
|
|
if ($firstTime) { |
65
|
|
|
echo 'Factor: ', sprintf("%d.3×", $time / $firstTime); |
66
|
|
|
echo ', Reverse Factor: ', sprintf("%d.3×", $firstTime / $time), '<br>'; |
67
|
|
|
} else { |
68
|
|
|
$firstTime = $time; |
69
|
|
|
} |
70
|
|
|
echo 'Average: ', $time / $iterations, '<br>'; |
71
|
|
|
echo 'MemoryPeak: ', memory_get_peak_usage(), ' (meaningful only if you run one benchmark at time)'; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
benchmark($replace, 'Engine benchmark'); |
75
|
|
|
benchmark($replaceSprintf, 'Engine Sprintf benchmark'); |
76
|
|
|
benchmark($sprintf, 'Sprintf benchmark'); |
77
|
|
|
benchmark($strReplace, 'StrReplace benchmark'); |
78
|
|
|
|