forked from AliShareei/smarty-vs-twig-benchmark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bench.php
executable file
·105 lines (84 loc) · 2.82 KB
/
bench.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env php
<?php
require __DIR__ . '/vendor/autoload.php';
function benchmark(string $type, int $iterations)
{
echo 'Benchmarking ' . $type . "\n";
$instance = setup($type);
$data = [
'data' => [
'some', 'bits', 'to', 'iterate', 'over'
]
];
// Prime the cache
$result = benchmarkOnce($type, $instance, $data);
echo "Result:\n";
echo $result;
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
benchmarkOnce($type, $instance, $data);
}
$end = microtime(true);
echo "\n\n";
echo "Time taken: " . ($end - $start) . "\n";
echo "Time taken per iteration: " . (($end - $start) / $iterations) . "\n";
}
function setup($type)
{
switch ($type) {
case 'smarty':
$smarty = new Smarty\Smarty();
$smarty->setEscapeHtml(true);
$smarty->setCompileCheck(false);
$smarty->setCacheDir(__DIR__ . '/cache');
$smarty->setCompileDir(__DIR__ . '/cache');
return $smarty;
case 'smarty_reuse':
$smarty = new Smarty\Smarty();
$smarty->setEscapeHtml(true);
$smarty->setCompileCheck(false);
$smarty->setCacheDir(__DIR__ . '/cache');
$smarty->setCompileDir(__DIR__ . '/cache');
return $smarty->createTemplate('index.html.smarty');
case 'twig':
$loader = new \Twig\Loader\FilesystemLoader('templates');
return new \Twig\Environment($loader, [
'cache' => __DIR__ . '/cache',
]);
case 'twig_reuse':
$loader = new \Twig\Loader\FilesystemLoader('templates');
$env = new \Twig\Environment($loader, [
'cache' => __DIR__ . '/cache',
]);
return $env->load('index.html.twig');
default:
throw new InvalidArgumentException('Unknown type');
}
}
function benchmarkOnce($type, $instance, $data)
{
switch ($type) {
case 'smarty':
/** @var Smarty\Smarty $instance */
$instance->assign($data);
return $instance->fetch('index.html.smarty');
case 'smarty_reuse':
/** @var Smarty\Template $instance */
$instance->assign($data);
return $instance->fetch();
case 'twig':
/** @var Twig_Environment $instance */
$template = $instance->load('index.html.twig');
return $template->render($data);
case 'twig_reuse':
/** @var Twig_TemplateWrapper $instance */
return $instance->render($data);
default:
throw new InvalidArgumentException('Unknown type');
}
}
exec('rm -rf cache');
exec('mkdir cache');
$type = $argv[1] ?? null;
$iterations = (int) ($argv[2] ?? 100000);
benchmark($type, $iterations);