I do not see a way to make it much faster, but still: do not compute the division several times. Also, if you comment the defined $a and defined $w and part in my code, the sub will run about 5% faster, but you should be sure your input does not contain any invalid lines.
#!/usr/bin/perl use warnings; use strict; use Benchmark 'cmpthese'; sub arivu { my $input = shift; open my $FH, '<', $input or die; my $minimumAmount = 1e12; my ($amount, $weight); while (<$FH>) { if (/(\d+) (\d+)/) { if ($minimumAmount > ($1/$2)) { $minimumAmount = $1 / $2; $amount = $1; $weight = $2; } } } close $FH; return "$amount\t$weight\n"; } # arivu sub choroba { my $input = shift; open my $FH, '<', $input or die; my $minimumAmount = 1e12; my ($amount, $weight); while (<$FH>) { my ($a, $w) = split; if (defined $a and defined $w and (my $ratio = $a / $w) < $minimumAmount) { $minimumAmount = $ratio; $amount = $a; $weight = $w; } } close $FH; return "$amount\t$weight\n"; } # choroba my $input; $input .= (join ' ', map int(1 + rand 1000), 1 .. 2) . "\n" for 1 .. 1 +000; cmpthese(-1, {arivu => sub {arivu \$input}, choroba => sub {choroba \$input}, }); print arivu \$input; print choroba \$input; __END__ Output: Rate arivu choroba arivu 466/s -- -17% choroba 565/s 21% -- 8 953 8 953

In reply to Re: code optimization by choroba
in thread code optimization by arivu198314

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.