http://qs1969.pair.com?node_id=24628


in reply to RE: Set String Length (benchmark)
in thread A Set String Length

I don't think substr is what he's looking for. That would chop off the end of the string, not pad it. But in the interest of benchmarking I ran the following.
use Benchmark; my $str = 'hello'; timethese( 10000000, { 'pack' => q{ $str = pack("A10",$str); }, 'sprintf' => q{ $str = sprintf("%-10s",$str); }, });
And got these results, not much of a difference.
Benchmark: timing 10000000 iterations of pack, sprintf... pack: 18 secs (16.86 usr 0.00 sys = 16.86 cpu) sprintf: 18 secs (17.36 usr 0.00 sys = 17.36 cpu)

Replies are listed 'Best First'.
benchmark comment
by perlmonkey (Hermit) on Jul 27, 2000 at 08:27 UTC
    Be careful with benchmark, your test is not a real test because your $str is lexical ... it is not defined in the 'pack' and 'sprintf' subroutines. You have to declare the lexical variable inside the routines. There can be significant differences between your test and a real test (although the pack and sprintf are still similar in performance):
    my $str = 'hello'; timethese( 1000000, { 'pack' => q{$str = pack("A10",$str); }, 'sprintf' => q{$str = sprintf("%-10s",$str); }, });
    Results:
    Benchmark: timing 1000000 iterations of pack, sprintf... pack: 3 wallclock secs ( 3.84 usr + 0.02 sys = 3.86 CPU) sprintf: 4 wallclock secs ( 4.24 usr + 0.00 sys = 4.24 CPU)
    The correct way:
    timethese( 1000000, { 'pack' => q{my $str = 'hello'; $str = pack("A10",$str); +}, 'sprintf' => q{my $str = 'hello'; $str = sprintf("%-10s",$str); +}, });
    Results:
    Benchmark: timing 1000000 iterations of pack, sprintf... pack: 6 wallclock secs ( 5.82 usr + 0.03 sys = 5.85 CPU) sprintf: 7 wallclock secs ( 6.80 usr + 0.01 sys = 6.81 CPU)
      Ah.. thanks for the tip, didn't even realize I was doing that.