Created
March 20, 2011 21:16
-
-
Save joshhartman/878687 to your computer and use it in GitHub Desktop.
Select Multiple Random Rows with MySQL PHP 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 | |
| $max = 100; | |
| $table = 'mytable'; | |
| $limit = $max; | |
| $mysql = mysql_connect('localhost', 'root', ''); | |
| mysql_query('USE test'); | |
| ?> | |
| <h2>Order By Rand()</h2> | |
| <?php | |
| // Start TIMER | |
| $stimer = explode( ' ', microtime() ); | |
| $stimer = $stimer[1] + $stimer[0]; | |
| ?> | |
| <?php mysql_query("SELECT * FROM {$table} ORDER BY RAND() LIMIT {$limit}"); ?> | |
| <?php | |
| // End TIMER | |
| $etimer = explode( ' ', microtime() ); | |
| $etimer = $etimer[1] + $etimer[0]; | |
| echo '<p>'; | |
| printf( "Execution Time: <b>%f</b> seconds.", ($etimer-$stimer) ); | |
| echo '</p>'; | |
| ?> | |
| <p> </p> | |
| <h2>Order By Rand() Alternative</h2> | |
| <?php | |
| // Start TIMER | |
| $stimer = explode( ' ', microtime() ); | |
| $stimer = $stimer[1] + $stimer[0]; | |
| ?> | |
| <?php mysql_query("SELECT * FROM {$table} WHERE RAND()<(SELECT (({$limit} / COUNT(*)) * 10) FROM {$table}) ORDER BY RAND() LIMIT {$limit}"); ?> | |
| <?php | |
| // End TIMER | |
| $etimer = explode( ' ', microtime() ); | |
| $etimer = $etimer[1] + $etimer[0]; | |
| echo '<p>'; | |
| printf( "Execution Time: <b>%f</b> seconds.", ($etimer-$stimer) ); | |
| echo '</p>'; | |
| ?> | |
| <p> </p> | |
| <h2>Inner Join</h2> | |
| <?php | |
| // Start TIMER | |
| $stimer = explode( ' ', microtime() ); | |
| $stimer = $stimer[1] + $stimer[0]; | |
| ?> | |
| <?php for($x=0; $x<$max; $x++){ ?> | |
| <?php mysql_query("SELECT t1.* FROM {$table} AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM {$table})) AS id) AS t2 WHERE t1.id >= t2.id LIMIT 1"); ?> | |
| <?php } ?> | |
| <?php | |
| // End TIMER | |
| $etimer = explode( ' ', microtime() ); | |
| $etimer = $etimer[1] + $etimer[0]; | |
| echo '<p>'; | |
| printf( "Execution Time: <b>%f</b> seconds.", ($etimer-$stimer) ); | |
| echo '</p>'; | |
| ?> | |
| <p> </p> | |
| <h2>User Variable</h2> | |
| <?php | |
| // Start TIMER | |
| $stimer = explode( ' ', microtime() ); | |
| $stimer = $stimer[1] + $stimer[0]; | |
| ?> | |
| <?php mysql_query("SELECT t.* FROM (SELECT ROUND(RAND() * (SELECT MAX(id) FROM {$table})) num, @num:=@num+1 FROM (SELECT @num:=0) AS a, {$table} LIMIT {$limit}) AS b, {$table} AS t WHERE b.num = t.id"); ?> | |
| <?php | |
| // End TIMER | |
| $etimer = explode( ' ', microtime() ); | |
| $etimer = $etimer[1] + $etimer[0]; | |
| echo '<p>'; | |
| printf( "Execution Time: <b>%f</b> seconds.", ($etimer-$stimer) ); | |
| echo '</p>'; | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment