in reply to Re6: Anyone use "xor" in conditionals?
in thread Anyone use "xor" in conditionals?

use Benchmark qw(cmpthese); sub rbyte { int rand 256 } my @unsorted; for (1..10000) { push @unsorted, join '.', rbyte, rbyte, rbyte, rbyte +} sub sort_by_ip_address { return sort { pack("C4",split(/\./,$a)) cmp pack("C4",split(/\./,$b) +) } @_ } sub sort_faster { return map {$_->[1]} sort {$a->[0] cmp $b->[0]} map {[(pack('C4',spl +it(/\./,$_))), $_]} @_ } my @sorted; cmpthese( 10, { ' slow' => sub { @sorted = sort_by_ip_address(@unsorted) }, 'faster' => sub { @sorted = sort_faster(@unsorted) }, }); __END__ $ perl fastip.pl Benchmark: timing 10 iterations of slow, faster... slow: 80 wallclock secs (40.79 usr + 0.00 sys = 40.79 CPU) @ 0 +.25/s (n=10) faster: 15 wallclock secs ( 6.95 usr + 0.06 sys = 7.01 CPU) @ 1 +.43/s (n=10) s/iter slow faster slow 4.08 -- -83% faster 0.701 482% --

Replies are listed 'Best First'.
Re^8: Anyone use "xor" in conditionals? (faster)
by tye (Sage) on Jul 15, 2003 at 20:59 UTC

    I suspect that this will be roughly twice as fast as yours:

    map { join ".", unpack "C*", $_ } sort map { pack "C*", split /\./, $_ } @ips;
    and Benchmark says...
    Rate slow faster tye slow 0.575/s -- -75% -83% faster 2.34/s 307% -- -32% tye 3.45/s 501% 48% --
    Drat, only 50% faster. (: Probably because the S. Transform is specially optimized these days.

    Full code in HTML comments at top of node so "download code" will fetch it for you.

                    - tye

      which is why i don't send in patches for this type of thing (slow but not broken). the actual fastest i've found is almost the most simple...

      use Socket qw( inet_aton inet_ntoa ); sub sort_sock { map { inet_ntoa($_) } sort map { inet_aton($_) } @_ }

      which give me:

             s/iter faster    tye   sock
      faster   2.06     --   -29%   -64%
      tye      1.46    41%     --   -49%
      sock    0.737   179%    98%     --
      

      can it get better? will locale settings mess with the sort? will Unicode bite me? i'm unsure.

        ++ zengargoyle!

        Using inet_aton and inet_ntoa for this is very elegant. I'll have to keep that trick in mind.


        Mike
Re8: Anyone use "xor" in conditionals?
by dragonchild (Archbishop) on Jul 15, 2003 at 20:36 UTC
    Have you sent in the patch?

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.