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


in reply to A Set String Length

print substr($String, 0, 10);
<Update> SteveAZ98 is right: substr will not pad the string to a fixed length, if it is not longer than the desired width...</Update>

Engaging in one of my favorite PM activities, I benchmarked pack vs. substr:

timethese(1000000, { pack => q{ my $String = 'Russ is a stud'; $String = pack("A10", $S +tring)}, substr => q{ my $String = 'Russ is a stud'; $String = substr($String +, 0, 10)} });
With these results:
Benchmark: timing 1000000 iterations of pack, substr... pack: 7 wallclock secs ( 7.20 usr + 0.00 sys = 7.20 CPU) substr: 6 wallclock secs ( 6.67 usr + 0.01 sys = 6.68 CPU)
I just love wasting time with benchmarks, perl golf, etc.

Russ
Brainbench 'Most Valuable Professional' for Perl

Replies are listed 'Best First'.
RE: RE: Set String Length (benchmark)
by steveAZ98 (Monk) on Jul 27, 2000 at 08:08 UTC
    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)
      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.