Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 594  / 1 Year ago, sun, december 18, 2022, 4:55:07

In order to run a few benchmarks on my newly installed 13.04, I wrote the below fibonacci script in python. It basically accepts a number and starts crunching fibonacci numbers that many times:



#!/usr/bin/python
import time
from time import time

def fibo(n):
a,b,i=0,1,0
while i<n:
#print b
a,b = b,b+a
i+=1


if __name__ == "__main__":
s=time()
fibo(1000000)
print round((time()-s)*1000,0),"ms"


However, when the fibo() function is called with 1 million as parameter, the python seems to hang. While, this similar code in java runs instantly:



class fibonacci
{
private static void fibo(int n)
{
int a=0,b=1,i=0;
while( i<n)
{
//print b
int t=a;
a=b;
b=b+t;
i++;
}
}

public static void main(String[] args)
{
float s=System.currentTimeMillis();
fibo(1000000);
System.out.println( (System.currentTimeMillis()-s) + "ms");
}
}


What is the reason for this? Is python inherently that slow or is something wrong with my raring installation ?


More From » 13.04

 Answers
4

Looking at your Java code, I notice you are using int for the Fibonacci numbers.
On the other hand, Python is using arbitrary precision.



Also notice that the Fibonacci numbers won't fit in an int variable for n > 46!
So the Java code isn't even calculating Fibonacci numbers for n > 46.



You should change the int for some bigger data type (an arbitrary precision one, maybe), before you make the comparison.



Conclusion, Java runs this much faster because it is calculating with ints (a fixed size data type), while Python is using more and more RAM to accumulate for the ever increasing numbers (which eventually cease to fit in a 32-bit integer).



Try this:



#!/usr/bin/python
from time import time

def int32(x):
x &= 0xffffffff
if x > 0x7fffffff:
return - ( ~(x - 1) & 0xffffffff )
else:
return x

def fibo(n):
a,b,i=0,1,0
while i<n:
t = a
a = b
b = int32(b + t)
i+=1


if __name__ == "__main__":
s=time()
fibo(1000000)
print round((time()-s)*1000,0),"ms"


to see approximately how much time would it take if Python used ints.


[#30635] Monday, December 19, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kroapathe

Total Points: 445
Total Questions: 117
Total Answers: 99

Location: Botswana
Member since Sun, Sep 19, 2021
3 Years ago
;