SPUG:Max of two floats?

Marc M. Adkins Marc.M.Adkins at Doorways.org
Tue Jan 28 23:02:50 CST 2003


> >I couldn't find a max(,) function in Perl, so should I use the ?
> >operator? I was thinking something like this might be fastest:
>
> use List::Util 'max';
>
> List::Util is part of Scalar-List-Utils, available on CPAN and also
> included in the perl distribution as of 5.8.0.

The attached script rates the inline conditional operator as about 3-4 times
faster than the List::Util::max() call for two arguments.  I'm figuring the
inline conditional operator gets optimized into good code whereas the max()
call does stack operations and so forth.  And yes, the inline conditional is
what I generally use since Perl hasn't a max operator to my knowledge.

Results (slowest first):

	List::Util      (var int)         583771/s
	List::Util  (const float)         624220/s
	List::Util    (const int)         652742/s
	Conditional     (var int)        2222222/s
	Conditional   (const int)       16666667/s
	Conditional (const float)       20000000/s

My test platform is Windows 2K on a 600 Mhz Pentium III (I think) using
ActiveState Perl 5.8.  Your mileage may vary.

mma

- the script -------------------------------------------------------

use     Benchmark   qw(cmpthese);
use     List::Util  qw(max);

$alpha = 23;
$bravo = 13;

$results = cmpthese(1_000_000,
    {
    'Conditional   (const int)' => sub
        {
        23 > 13 ? 23 : 13
        },
    'List::Util    (const int)' => sub
        {
        max(23, 13)
        },
    'Conditional (const float)' => sub
        {
        17.23 > 17.13 ? 17.23 : 17.13
        },
    'List::Util  (const float)' => sub
        {
        max(17.23, 17.13)
        },
    'Conditional     (var int)' => sub
        {
        $alpha > $bravo ? $alpha : $bravo
        },
    'List::Util      (var int)' => sub
        {
        max($alpha, $bravo)
        },
    }, 'none');

map {
    printf "%s %15s\n", $_->[0], $_->[1]
    } @$results;




More information about the spug-list mailing list