Do you happen to come from a C background ? In perl it's almost never a good idea to process a string as an array of characters. Building that array takes time and a lot of memory, and the operations you then do on it are rarely natural or fast (ok, a simple character walk is fast).

So the best way to solve this is to actually have the sequence in a plain string, and walk that string in a perlish way. Here substr() seems a good operator (you can also use a pattern match that selects 2 chars at a time, but that turns out to be slower).

Making perl fast is also to a great extent reducing the amount of opcodes that get executed. So your multiple if tests want to be replaced by something that takes less operations. As pointed out by the other answers, you can use a hash here. While a hash lookup is slightly more work than a simple test, it only has to be done once.

So the code becomes:

my %count; $count{substr($genome, $_, 2)}++ for 0..length($genome)-2; # Next combine the counts like in the original code # is this a bug or intentional ? $count{tt} += $count{aa}; $count{ag} += $count{ct}; $count{ac} += $count{gt}; $count{tg} += $count{ca}; $count{ga} += $count{tc}; $count{cc} += $count{gg};
This is about 4 times as fast as an array based solution using a hash on my perl.

If this still isn't fast enough, you can start looking at things like Inline::C.


In reply to Re: how can I speed up this perl?? by thospel
in thread how can I speed up this perl?? by Anonymous Monk

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.