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