methods of addition in Python

Ishwor ishwor.gurung at gmail.com
Sat Dec 25 23:21:02 EST 2004


As my earlier mail didn't make it c.l.py because it had the heading
"LIST Addition compared", probably it was blocked by the mail server.
;-)
anyway heres it again.. Sorry for people reading it again. Its the same post.

Hi all
I have just wrote a small script to compare the speed of list addition methods.
heres what it looks like.

#listadditioncompare.py
#compare the speeds of 3 different type of list element addition
import time
def method(TYPE):
   l1 = [];
   l2 = [];
   l3 = [];

   if TYPE == 1:
       finish = 0;
       start = 0;
       start = time.time();
       for y in range(0,3):
           for x in range(0,10000):
               l1 = l1 + [x];# type 1
           l1 = [];
           finish += time.time();
       averageFinish = finish/3;
       #m = float(finish-start);
       print "Method 1 done in (average finish time(out of 3)) -
%.10f" %(averageFinish-start);

   if TYPE == 2:
       finish = 0;
       start = 0;
       start = time.time();
       for y in range(0,3):
           for x in range(0,10000):
               l2 = l2 + [x];# type 2
           l2 = [];
           finish += time.time();
       averageFinish = finish/3;
       #m = float(finish-start);
       print "Method 2 done in (average finish time(out of 3)) -
%.10f" %(averageFinish-start);

   if TYPE == 3:
       finish = 0;
       start = 0;
       start = time.time();
       for y in range(0,3):
           for x in range(0,10000):
               l3 +=  [x];# type 3
           l3 = [];
           finish += time.time();
       averageFinish = finish/3;
       #m = float(finish-start);
       print "Method 3 done in (average finish time(out of 3)) -
%.10f" %(averageFinish-start);

print "@@@@@@@";
method(1);
method(2);
method(3);
print "@@@@@@@";

So far i think it does good. Running it 3 times gives

>>>
@@@@@@@
Method 1 done in (average finish time(out of 3)) - 1.1560001373
Method 2 done in (average finish time(out of 3)) - 1.1619999409
Method 3 done in (average finish time(out of 3)) - 0.0106666088
@@@@@@@

>>>
@@@@@@@
Method 1 done in (average finish time(out of 3)) - 1.1610000134
Method 2 done in (average finish time(out of 3)) - 1.1253333092
Method 3 done in (average finish time(out of 3)) - 0.0156667233
@@@@@@@
>>>

>>>
@@@@@@@
Method 1 done in (average finish time(out of 3)) - 1.1563334465
Method 2 done in (average finish time(out of 3)) - 1.1716668606
Method 3 done in (average finish time(out of 3)) - 0.0106668472
@@@@@@@
>>>

So i can assume that type 3 ( l3 += [x] ) addition is the fastest . Is
there anything i am doing wrong?? Also could this code be beautified
&& shortened??
Thanks.


-- 
cheers,
Ishwor Gurung



More information about the Python-list mailing list