Please tell me how to make the Python code below to compute the Fibonacci sequence run faster?
#!/usr/bin/perl
#-------------------------------------------------------------------------------
Perl vs Python execution time on Fibonacci sequence - run from command line
#-------------------------------------------------------------------------------
use warnings FATAL => qw(all);
use strict;
use Carp;
use Data::Dump qw(dump);
use Data::Table::Text qw(:all);
use feature qw(say current_sub);
use Time::HiRes qw(time);
my $N = 1e6; # Limit
if (my $p = time) # Python
{my $f = owf(undef, <<END);
import math
N = $N
prev, current = (0,1)
for i in range(N) :
(prev, current) = (current, prev + current)
print(f"Python length: {len(str(current))}, last: {str(current)[-10:]}\n")
END
say STDERR qq(\n\nPython\n\n);
say STDERR qx(python3 $f);
say STDERR "Python took: ", time-$p;
}
if (my $p = time) # Perl
{my $f = owf(undef, <<‘END’ =~ s(NNNN) ($N)gsr);
use Math::GMP qw(:constant);
my $N = NNNN;
my ($prev, $current) = (1, 0);
for (0…$N)
{($prev, $current) = ($current, $prev + $current);
}
print "Perl length: ", length($current), ", last: ", substr($current, -10), “\n”;
END
say STDERR qq(\n\nPerl\n\n);
say STDERR qx(perl $f);
say STDERR "Perl took: ", time-$p;
}
DATA
Python
Python length: 208988, last: 4926937501
Python took: 9.31476497650146
Perl
Perl length: 208988, last: 4926937501
Perl took: 3.88902902603149