14

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.

Community
  • 1
  • 1
Viacheslav Kondratiuk
  • 8,493
  • 9
  • 49
  • 81

1 Answers1

14

You won't replicate this in PHP. End of story. The reason is that the Java RTS uses JiT compilation techniques to compile the Java intermediate code down to the underlying X86 order code. This underlying order code will expose these branch prediction artefacts.

The PHP runtime system compiles PHP down to a bytecode which is a pseudo machine code that is interpreted. This interpreter will execute of the order of 0.5M opcodes /sec on a typical single core -- that is each PHP opcode takes perhaps 2-6K native instructions. Any subtleties of branching will be lost in this.

TerryE
  • 10,724
  • 5
  • 26
  • 48
  • 1
    possible **tl;dr**: PHP is interpreted fast enough that branch prediction doesn't make a noticeable difference. – Jon Egeland Jul 02 '12 at 17:57
  • 4
    Jon, your response doesn't make sense. Branch prediction _is_ being exploited within the PHP interpreter to accelerate its performance. But at an order code level `if ($array[$i] <= 150000)` compiles down to a FETCH_DIM_R, IS_SMALLER_OR_EQUAL, JMPZ code sequence, and H/W branch prediction does not impact the runtime of the JMPZ execution. – TerryE Jul 03 '12 at 08:57
  • @terryE: so so you have an example code, where branch prediction has an effect? – rubo77 Dec 30 '19 at 11:24