Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Perl script performance help

by Ratazong (Monsignor)
on Jul 05, 2016 at 09:32 UTC ( #1167219=note: print w/replies, xml ) Need Help??

in reply to Perl script performance help

Hi G0G0

Why do you need the @array? You could improve the required memory by changing

my @array = (1..1000000000); foreach (@array) {
foreach (1..1000000000) {
(The first solution gives an "out of memory" on my system, the later runs in 50 seconds with an empty loop).

Inside the loop, you can probably save some time by reversing only once, and storing the intermediate result in a temporary variable. And based on the size of the current number, you could determine which of the substr-lines is relevant and skip the others...

HTH, Rata

Replies are listed 'Best First'.
Re^2: Perl script performance help
by G0G0 (Initiate) on Jul 05, 2016 at 10:03 UTC
    Hi Rata thanks for the help, you are right your approach saved me a lot of memory, but i dont really understand what you mean in the last paragraph. thanks George

      He was suggesting you don't have to do the reverse 7 times. I don't think that's true.

      He also suggested you test the size of the variable and don't perform the substr() commands that will just return undef.

      my $start_run = time(); use strict; use Benchmark; use warnings; my @array = (1..1000000000); foreach (@array) { for(my $i=1; $i<length($_);$i++) { if ($_==reverse(substr($_, 0, $i) * substr($_, $i))) { print $_."\n" ;} } } my $end_run = time(); my $run_time = $end_run - $start_run; print "Time taken: ".$run_time." sec\n";
      But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)

        now i understand, thanks for the help but the funny thing is that it take more time than before

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1167219]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2020-06-05 00:35 GMT
Find Nodes?
    Voting Booth?
    Do you really want to know if there is extraterrestrial life?

    Results (35 votes). Check out past polls.