in reply to Re: Duff's Device
in thread Duff's Device
It's meaningless in Perl, except as an anecdote, because the virtual machine has so many branches at the machine code level no matter what code you write, and no additional expensive penalty for jumping around in Perl code.It's not just the jumping you save on, it's also the reduced testing. Duff's device does two things: it does loop unrolling, and it uses a neat/tricky way of dealing with the border case of a loop unrolling technique. Loop unrolling pays because of not having to evaluate a condition. Here's a benchmark showing duff's device to be significant faster than a plain loop (yes, the work done is contrived, but that's not the point):
#!/usr/bin/perl use strict; use warnings; use Benchmark qw /timethese cmpthese/; our ($x, $y); our $N = shift || 100; cmpthese -1 => { noduff => '$x = 0; my $n = $N; while ($n --) {$x ++}', duff => '$y = 0; my $n = int (($N + 7) / 8); goto "LABEL" . ($N % 8); { LABEL0: $y ++; LABEL7: $y ++; LABEL6: $y ++; LABEL5: $y ++; LABEL4: $y ++; LABEL3: $y ++; LABEL2: $y ++; LABEL1: $y ++; redo if -- $n > 0 }', }; die "Unequal \$N == $N; \$x == $x; \$y == $y.\n" unless $N == $x && $N + == $y; __END__ Rate noduff duff noduff 39384/s -- -42% duff 68267/s 73% --
Abigail
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Duff's Device
by halley (Prior) on Feb 24, 2004 at 14:32 UTC | |
by Abigail-II (Bishop) on Feb 24, 2004 at 14:43 UTC | |
|
Re: Re: Duff's Device
by demerphq (Chancellor) on Feb 24, 2004 at 18:13 UTC | |
by Abigail-II (Bishop) on Feb 24, 2004 at 19:43 UTC |