benchmark.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. if ( ! isset($_SERVER['argv'][1], $_SERVER['argv'][2])) {
  3. echo 'Usage: php benchmark.php <format> <iterations> [output-file]'.PHP_EOL;
  4. exit(1);
  5. }
  6. list(, $format, $iterations) = $_SERVER['argv'];
  7. require_once 'bootstrap.php';
  8. function benchmark(\Closure $f, $times = 10) {
  9. $time = microtime(true);
  10. for ($i=0; $i<$times; $i++) {
  11. $f();
  12. }
  13. return (microtime(true) - $time) / $times;
  14. }
  15. function createCollection() {
  16. $collection = array();
  17. for ($i=0; $i<50; $i++) {
  18. $collection[] = createObject();
  19. }
  20. return $collection;
  21. }
  22. function createObject() {
  23. $post = new \JMS\Serializer\Tests\Fixtures\BlogPost('FooooooooooooooooooooooBAR', new \JMS\Serializer\Tests\Fixtures\Author('Foo'), new \DateTime);
  24. for ($i=0; $i<10; $i++) {
  25. $post->addComment(new \JMS\Serializer\Tests\Fixtures\Comment(new \JMS\Serializer\Tests\Fixtures\Author('foo'), 'foobar'));
  26. }
  27. return $post;
  28. }
  29. $serializer = \JMS\Serializer\SerializerBuilder::create()->build();
  30. $collection = createCollection();
  31. $metrics = array();
  32. $f = function() use ($serializer, $collection, $format) {
  33. $serializer->serialize($collection, $format);
  34. };
  35. // Load all necessary classes into memory.
  36. benchmark($f, 1);
  37. printf('Benchmarking collection for format "%s".'.PHP_EOL, $format);
  38. $metrics['benchmark-collection-'.$format] = benchmark($f, $iterations);
  39. $output = json_encode(array('metrics' => $metrics));
  40. if (isset($_SERVER['argv'][3])) {
  41. file_put_contents($_SERVER['argv'][3], $output);
  42. echo "Done.".PHP_EOL;
  43. } else {
  44. echo $output.PHP_EOL;
  45. }