RE: Re: negative numbers

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



To view the terms under which this email is distributed, please go to http://disclaimer.leedsmet.ac.uk/email.htm



> -----Original Message-----
> From: Jason Wong
> Sent: 27/12/04 10:16
> 
> On Monday 27 December 2004 12:40, Richard Lynch wrote:
> 
> > If you want to mimic the behaviour of abs (allowing for positive
> numbers)
> > and performance was an issue, that:
> > $x = ($x < 0) ? - $x : $x;
> >
> > is most likely faster than abs()
> 
> Having nothing better to do I decided to benchmark this:
> 
> ternary:
> 
>     $doo = -20;
>     for ($i = 1; $i < 10000000; $i++) {
>         $dah = ($doo < 0) ? - $doo : $doo;
>     }
> 
> abs():
> 
>     $doo = -20;
>     for ($i = 1; $i < 10000000; $i++) {
>         $dah = abs($doo);
>     }

That's not a valid benchmark, since only on the first pass through the loop
is $doo negative.  Personally, I'd want to test it with equal numbers of
positive and negative values, and I'd want to know the contribution of the
loop and value-setup overhead, so I'd write it like this:

    $t = microtime();
    $oh = $t[1] + $t[0];
    for ($i=1; $i<10000000; $i++) {
        $doo = 20 * ($i%2?-1:1);
    }
    $t = microtime();
    $oh = $t[1] + $t[0] -$oh;

    $t = microtime();
    $tern = $t[1] + $t[0];
    for ($i=1; $i<10000000; $i++) {
        $doo = 20 * ($i%2?-1:1);
        $dah = ($doo<0) ? -$doo : $doo;
    }
    $t = microtime();
    $tern = $t[1] + $t[0] -$tern;

    $t = microtime();
    $abs = $t[1] + $t[0];
    for ($i=1; $i<10000000; $i++) {
        $doo = 20 * ($i%2?-1:1);
        $dah = abs($doo);
    }
    $t = microtime();
    $tern = $t[1] + $t[0] - $abs;

    echo "<p>Overhead = ", number_format($oh, 2), "sec<br />\n";
    echo "Ternary = ", number_format($tern, 2),
         " sec; less overhead = ", number_format($tern-$oh, 2),
         " sec<br />\n";
    echo "Abs() = ", number_format($abs, 2),
         " sec; less overhead = ", number_format($abs-$oh, 2),
         " sec\n</p>";

I don't have access to a php system right now, or I'd run it (just out of
curiosity!).  Anyone who wants to grab the above and test it is welcome...
;)

Cheers!

Mike

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux