1<?php
2
3declare(strict_types=1);
4
5use JMS\Serializer\SerializerBuilder;
6use JMS\Serializer\Tests\Fixtures\Author;
7use JMS\Serializer\Tests\Fixtures\BlogPost;
8use JMS\Serializer\Tests\Fixtures\Comment;
9use JMS\Serializer\Tests\Fixtures\Publisher;
10
11if (!isset($_SERVER['argv'][1], $_SERVER['argv'][2])) {
12    echo 'Usage: php benchmark.php <format> <iterations> [output-file]' . PHP_EOL;
13    exit(1);
14}
15
16[, $format, $iterations] = $_SERVER['argv'];
17
18require_once 'bootstrap.php';
19
20function benchmark(Closure $f, $times = 10)
21{
22    $time = microtime(true);
23    for ($i = 0; $i < $times; $i++) {
24        $f();
25    }
26
27    return (microtime(true) - $time) / $times;
28}
29
30function createCollection()
31{
32    $collection = [];
33    for ($i = 0; $i < 200; $i++) {
34        $collection[] = createObject();
35    }
36
37    return $collection;
38}
39
40function createObject()
41{
42    $p = new Publisher('bar');
43    $post = new BlogPost('FooooooooooooooooooooooBAR', new Author('Foo'), new DateTime(), $p);
44    for ($i = 0; $i < 100; $i++) {
45        $post->addComment(new Comment(new Author('foo'), 'foobar'));
46    }
47
48    return $post;
49}
50
51$serializer = SerializerBuilder::create()->build();
52$collection = createCollection();
53$metrics = [];
54$f = static function () use ($serializer, $collection, $format) {
55    $serializer->serialize($collection, $format);
56};
57
58// Load all necessary classes into memory.
59benchmark($f, 1);
60
61printf('Benchmarking collection for format "%s".' . PHP_EOL, $format);
62$metrics['benchmark-collection-' . $format] = benchmark($f, $iterations);
63
64$output = json_encode(['metrics' => $metrics]);
65
66if (isset($_SERVER['argv'][3])) {
67    file_put_contents($_SERVER['argv'][3], $output);
68    echo 'Done.' . PHP_EOL;
69} else {
70    echo $output . PHP_EOL;
71}
72