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)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.