Created
April 9, 2011 17:51
-
-
Save aaronpk/911605 to your computer and use it in GitHub Desktop.
SQL Connect Benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Set up your database connection | |
| define('PDO_DSN', 'mysql:dbname=test;host=127.0.0.1'); | |
| define('PDO_USER', 'root'); | |
| define('PDO_PASS', ''); | |
| /****** | |
| Output will be something like this: | |
| $ php sql-benchmark.php | |
| Finished in 5668 ms | |
| avg connect: 1368 microseconds | |
| avg prepare: 56 microseconds | |
| avg execute: 305 microseconds | |
| avg fetch: 4 microseconds | |
| Measurement took 1591 microseconds | |
| ******/ | |
| // Measuring the measurement time | |
| $measurement = 0; | |
| class AverageCalculator { | |
| public $total; | |
| private $count; | |
| public function add($value) { | |
| $tick = microtime(TRUE); | |
| $this->total += $value; | |
| $this->count++; | |
| global $measurement; | |
| $measurement += microtime(TRUE) - $tick; | |
| } | |
| public function avg() { | |
| return $this->total / $this->count; | |
| } | |
| } | |
| $timings = array( | |
| 'connect' => new AverageCalculator(), | |
| 'prepare' => new AverageCalculator(), | |
| 'execute' => new AverageCalculator(), | |
| 'fetch' => new AverageCalculator() | |
| ); | |
| $start = microtime(TRUE); | |
| for($i=0; $i<100; $i++) { | |
| try { | |
| $tick = microtime(TRUE); | |
| $db = new PDO(PDO_DSN, PDO_USER, PDO_PASS); | |
| $timings['connect']->add(microtime(TRUE)-$tick); | |
| $tick = microtime(TRUE); | |
| $query = $db->prepare('SELECT DATE() AS d'); | |
| $timings['prepare']->add(microtime(TRUE)-$tick); | |
| $tick = microtime(TRUE); | |
| $query->execute(); | |
| $timings['execute']->add(microtime(TRUE)-$tick); | |
| $tick = microtime(TRUE); | |
| $query->fetch(); | |
| $timings['fetch']->add(microtime(TRUE)-$tick); | |
| // Sleep a little bit between connection attempts to not flood the mysql server | |
| usleep(rand(10000,100000)); | |
| } catch (PDOException $e) { | |
| die("Error connecting to database: " . $e->getMessage() . "\n"); | |
| } | |
| } | |
| $end = microtime(TRUE); | |
| $diff = $end - $start; | |
| echo "Finished in " . round($diff * 1000) . " ms\n"; | |
| foreach($timings as $k=>$v) { | |
| echo "\tavg " . $k . ": " . round($v->avg() * 1000000) . " microseconds\n"; | |
| } | |
| echo "Measurement took " . round($measurement * 1000000) . " microseconds\n"; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment