Thanks for the explanation about the float conversions and hash memoization.
The array lookup is quite a bit faster than the string index. I didn't see in the OP that the result had to be integers. The OP showed floats as the output. Edit: The array lookup method will work equally well with either floats or ints since the int() function is not in the part that does the lookup.
#!/usr/bin/env perl
use warnings;
use strict;
use Benchmark 'cmpthese';
my $lookup = join '', map{ chr( $_ / 255 * 100 ) } 0 .. 255;
my @lookup = map{ int( $_ / 255 * 100 ) } 0 .. 255;
my $const = 100 / 255;
cmpthese(-2, {
lookup => sub {
my @output = map { ord( substr $lookup, $_, 1 )} 0 .. 255;
},
calc => sub {
my @output = map {$_ / 255 * 100} 0 .. 255;
},
calc2 => sub {
my @output = map {$_ * $const} 0 .. 255;
},
arraylookup => sub {
my @output = map { $lookup[ $_ ] } 0 .. 255;;
},
});
my @output1 = map { ord( substr $lookup, $_, 1 )} 0 .. 5;
my @output2 = map {$_ * $const} 0 .. 5;
print "@output1\n";
print "@output2\n";
__END__
# Results on my machine (v5.22.1 built for MSWin32-x64-multi-thread):
Rate calc calc2 lookup arraylookup
calc 11990/s -- -25% -31% -47%
calc2 15929/s 33% -- -9% -30%
lookup 17496/s 46% 10% -- -23%
arraylookup 22838/s 90% 43% 31% --
0 0 0 1 1 1
0 0.392156862745098 0.784313725490196 1.17647058823529 1.5686274509803
+9 1.96078431372549
-
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
or How to display code and escape characters
are good places to start.
|