While I didn't bother to bench the C and Java versions, I can tell you there are many ways to speed this up.
Changing $i to a lexical gives you 10% more speed.
By using the pragma use integer in a lexically scoped block around the code you get
310% more speed.
It may not be a perfect number as I didn't not run the Java and C code, and there may be differences in implementation between my system and yours, but that would bring Perl down to 8 seconds which is a negligible difference.
More importantly, runtime is only a fraction of what matters in a real software project so comparing numbers like this is a really just mental wanking. And the fact that you go to a perl site to do it just says to me that your instigating which is pretty dumb. Would you go to an ethnic neighborhood and start slandering the locals? Not if you weren't looking for trouble.
#!/usr/bin/perl
use Benchmark qw(cmpthese timethese);
sub iterate {
open(FILE, ">", "file.txt");
for ($i = 0; $i < 1000000; $i ++) {
print FILE $i++;
}
close(FILE);
}
sub lex_iterate {
open(FILE, ">", "file.txt");
for (my $i = 0; $i < 1000000; $i ++) {
print FILE $i++;
}
close(FILE);
}
sub int_iterate {
use integer;
open(FILE, ">", "file.txt");
for (my $i = 0; $i < 1000000; $i ++) {
print FILE $i++;
}
close(FILE);
}
my $results = timethese(5 , { iterate=>\&iterate , lex_iterate=>\&lex_
+iterate, int_iterate=>\&int_iterate } );
cmpthese($results);
__END__
Benchmark: timing 5 iterations of int_iterate, iterate, lex_iterate...
int_iterate: 4 wallclock secs ( 4.03 usr + 0.06 sys = 4.09 CPU) @
+1.22/s (n=5)
iterate: 17 wallclock secs (16.70 usr + 0.07 sys = 16.77 CPU) @ 0
+.30/s (n=5)
lex_iterate: 15 wallclock secs (15.20 usr + 0.08 sys = 15.28 CPU) @
+0.33/s (n=5)
s/iter iterate lex_iterate int_iterate
iterate 3.35 -- -9% -76%
lex_iterate 3.06 10% -- -73%
int_iterate 0.818 310% 2
-Lee
"To be civilized is to deny one's nature."
-
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.