a pastebin project

Benchmark PDO(mysql) vs mysqli()

  1. <?php
  2.  
  3. // Which query to test?
  4. //$sql = "SELECT NULL";
  5. $sql = "SHOW TABLE STATUS";
  6. //$sql = "SELECT * FROM users";
  7.  
  8. // Your database credentials
  9. $dbname = 'database';
  10. $dbuser = 'username';
  11. $dbpass = 'password';
  12.  
  13. // How many times to run the tests?
  14. $runs = 10000;
  15.  
  16. // Wait how many seconds before ending the script?
  17.  
  18. // Don't render as HTML
  19. header('Content-Type: text/plain');
  20.  
  21. function testMySQLi() {
  22.         global $dbuser,$dbpass,$dbname,$sql;
  23.         $start = microtime(1);
  24.  
  25.         $mdb = new mysqli('localhost',$dbuser,$dbpass,$dbname);
  26.         $result = $mdb->query($sql);
  27.         while ($row = $result->fetch_row())
  28.         //while ($row = $result->fetch_array()) // fetch_row() is faster but not available in PDO
  29.                 continue;
  30.  
  31.         return microtime(1)-$start;
  32. }
  33.  
  34. function testPDO() {
  35.         global $dbuser,$dbpass,$dbname,$sql;
  36.         $start = microtime(1);
  37.                
  38.         $pdb = new PDO('mysql:host=localhost;dbname='.$dbname,$dbuser,$dbpass);
  39.         foreach ($pdb->query($sql) as $row)
  40.                 continue;
  41.        
  42.         return microtime(1)-$start;
  43. }
  44.  
  45. $Ms = $Ps = array();
  46. for ($c=-5;$c<=$runs;$c++) {
  47.  
  48.         $Ms[] = testMySQLi();
  49.         $Ps[] = testPDO();
  50.        
  51.         // Ignore the first few runs
  52.         if ($c==0) $Ps = $Ms = array();
  53. }
  54.  
  55. echo "# of runs: $runs\n";
  56.  
  57. $Mt = array_sum($Ms);
  58. echo "Total time for mysqli(): $Mt\n";
  59. //print_r($Ms);
  60.  
  61. $Pt = array_sum($Ps);
  62. echo "Total time for PDO(): $Pt\n";
  63. //print_r($Ps);
  64.  
  65. $diff = abs($Pt-$Mt);
  66. if ($Mt<$Pt) echo "mysqli was faster by $diff seconds.\n";
  67. else if ($Pt<$Mt) echo "PGO was faster by $diff seconds.\n";
  68. else echo "The times were equal!\n";

advertising

Create a Paste

Please enter your new post below (or upload a file instead):





Please note that information posted here will not expire by default. If you want it to expire, please set the expiry time above. If it is set to expire, web search engines will not be allowed to index it prior to it expiring. Items that are not marked to expire will be indexable by search engines. Be careful with your passwords.

fantasy-obligation
fantasy-obligation