You should "use vars" to allow Benchmark to use the variables you want it to use.sub traditional { my $C = $A; $A = $B; $B = $C; } sub non_trad { ($B, $A) = ($A, $B); } Global symbol "$A" requires explicit package name at ./bench.perl line + 12. Global symbol "$B" requires explicit package name at ./bench.perl line + 13.
This doesn't change the results, though, since you were (unknowingly) using "real" variables, anyway.
Here are some more possibilities, just to play around:
#!/usr/bin/perl -w use vars qw/$A $B @Arr/; use strict; use Benchmark; $A = rand(10); $B = rand(10); @Arr = ($A, $B); sub traditional { my $C = $A; $A = $B; $B = $C; } sub non_trad { ($B, $A) = ($A, $B); } sub array_slice1 { @Arr = @Arr[1,0]; } sub array_slice2 { @Arr[1,0] = @Arr; } timethese (100000, { "traditional" => \&traditional, "not traditional" => \&non_trad, "array1" => \&array_slice1, "array2" => \&array_slice2, }); Results: Benchmark: timing 100000 iterations of array1, array2, not traditional +, traditional... array1: 4 wallclock secs ( 3.98 usr + 0.00 sys = 3.98 CPU) array2: 3 wallclock secs ( 3.27 usr + 0.00 sys = 3.27 CPU) not traditional: 2 wallclock secs ( 2.72 usr + 0.00 sys = 2.72 CPU) traditional: 2 wallclock secs ( 1.81 usr + 0.00 sys = 1.81 CPU)
Russ
Brainbench 'Most Valuable Professional' for Perl
In reply to RE: simple swap...
by Russ
in thread simple swap...
by eduardo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |