I ran each block of code thru 100 tests of 1000 iterations (100,000 total executions). Your code was 0.0087 seconds faster. Tests were run on an idle dual Xeon 2.4Ghz.
Mine (words.php)
Yours (words2.php)
Mine (words.php)
Code:
<?php
$tests = 100;
$iterations = 1000;
$results = array();
for($y = 1; $y <= $tests; $y++)
{
$time_start = microtime(true);
for($z = 1; $z <= $iterations; $z++)
{
$source = explode("\n", file_get_contents("words.txt"));
$words = array();
for($i = 0; $i < count($source); $i++)
{
$line = explode(",",$source[$i]);
$words[] = array($line[0],$line[1]);
}
shuffle($words);
$word = $words[0];
//echo $z.'. '.$word[0].', '.$word[1].'<br>';
}
$time_end = microtime(true);
$time = $time_end - $time_start;
$results[] = $time;
}
$avgtime = array_sum($results) / count($results);
echo '<h1>Executed '.$tests.' tests in an average of '.$avgtime.' seconds each.</h1>';
Yours (words2.php)
Code:
<?php
$tests = 100;
$iterations = 1000;
$results = array();
for($y = 1; $y <= $tests; $y++)
{
$time_start = microtime(true);
for($z = 1; $z <= $iterations; $z++)
{
$compare = file('words2.txt');
//the number of rows in the file.
$num = count($compare);
//randomly generate a pair to display.
$position = rand(0,$num);
// to test whether $number is odd you could use the arithmetic
// operator '%' (modulus) like this
if($odd = $position % 2)
{
// $odd == 1. We need to decrease our $position in the file.
$second = $compare[$position];
$position--;
$first = $compare[$position];
}
else
{
// $odd == 0. We are where we need to be in the file.
$first = $compare[$position];
$position++;
$second = $compare[$position];
}
//echo $z.'. '.$first.', '.$second.'<br>';
}
$time_end = microtime(true);
$time = $time_end - $time_start;
$results[] = $time;
}
$avgtime2 = array_sum($results) / count($results);
echo '<h1>Executed '.$tests.' tests in an average of '.$avgtime2.' seconds each.</h1>';
Code:
<?php
require('words.php');
require('words2.php');
$diff = $avgtime - $avgtime2;
echo '<h1>Difference: '.$diff;