benchmark.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. $p = new \JMS\Serializer\Tests\Fixtures\Publisher('bar');
  27. $post = new \JMS\Serializer\Tests\Fixtures\BlogPost('FooooooooooooooooooooooBAR', new \JMS\Serializer\Tests\Fixtures\Author('Foo'), new \DateTime, $p);
  28. for ($i=0; $i<10; $i++) {
  29. $post->addComment(new \JMS\Serializer\Tests\Fixtures\Comment(new \JMS\Serializer\Tests\Fixtures\Author('foo'), 'foobar'));
  30. }
  31. return $post;
  32. }
  33. $serializer = \JMS\Serializer\SerializerBuilder::create()->build();
  34. $collection = createCollection();
  35. $metrics = array();
  36. $f = function() use ($serializer, $collection, $format) {
  37. $serializer->serialize($collection, $format);
  38. };
  39. // Load all necessary classes into memory.
  40. benchmark($f, 1);
  41. printf('Benchmarking collection for format "%s".'.PHP_EOL, $format);
  42. $metrics['benchmark-collection-'.$format] = benchmark($f, $iterations);
  43. $output = json_encode(array('metrics' => $metrics));
  44. if (isset($_SERVER['argv'][3])) {
  45. file_put_contents($_SERVER['argv'][3], $output);
  46. echo "Done.".PHP_EOL;
  47. } else {
  48. echo $output.PHP_EOL;
  49. }