Just read a great post about branch prediction. I was trying to reproduce it using php language.
<?php
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
$count = 300000;
$sum = 0;
for ($i = 0; $i <= $count; $i++) {
$array[] = rand(0, $count);
}
sort($array);
for ($i = 0; $i <= $count; $i++) {
if ($array[$i] <= 150000) {
$sum += $array[$i];
}
}
$time_end = microtime_float();
$time = $time_end - $time_start;
echo $sum . '<br />';
echo 'End:' . $time;
?>
But I always get the same results with sorting and without it. Maybe I'm doing something wrong? Or maybe php has built in optimization for branch predictor?
UPD:
I made code modifications according to comments and measure the time on my local machine.
Not sorted array: 1.108197927475
Sorted array: 1.6477839946747
Difference: 0.539586067.
I think this difference spent on sorting. It looks like true that branch predictor has no impact on speed.