[BangPypers] python speed comparison
Emil Chacko
emilchacko at gmail.com
Fri Jul 23 09:56:37 CEST 2010
Below given is solution to a puzzle(
http://projecteuler.net/index.php?section=problems&id=14) in python and c
Python:
import time
startT=time.time()
maxlen=0
longest=0
for i in xrange(1,1000000):
last=i
cnt=0
while(last <> 1):
cnt=cnt+1
if(last%2==0):
last=last/2
else:
last=3*last+1
if(cnt>maxlen):
maxlen=cnt
longest=i
print "time taken (sec) : ",time.time()-startT
print maxlen,longest
Python Output:
time taken (sec) : 99.4702298641
524 837799
C:
#include <stdio.h>
int main(int argc, char **argv)
{
int longest = 0;
int maxlen = 0;
int i;
unsigned long last;
for (i = 1; i <= 1000000; i++)
{
last = i;
int cnt = 0;
while (last != 1)
{
cnt++;
if (last % 2 == 0)
last = last / 2;
else
last = 3 * last + 1;
}
if (cnt > maxlen)
{
maxlen = cnt;
longest = i;
}
}
printf("longest: %d (%d)\n", longest, maxlen);
return 0;
}
My doubt is that in C the result comes in 1-2 sec but in python it takes 99
secs.I don't expect python to be as fast as c but i cant understand why it
should be so slow in python.i'm new to python so if there is better way to
do the above prog in python please suggest.
More information about the BangPypers
mailing list