Timing Difference: insert vs. append & reverse

John Keeling johnfkeeling at yahoo.com
Mon Aug 2 13:30:44 CEST 2004


Dear all,
I tried the test program below. My interest is to examine timing
differences between insert vs. append & reverse for a list. My results
on my XP Python 2.3.4 are as follows:
time_reverse  0.889999389648
time_insert  15.7750005722
Over multiple runs ... the time taken to insert at the head of a list,
vs. the time taken to append to a list and then reverse it is
typically 16 or 17 times longer.
I would have expected the insert operation to be faster than the
combined append & reverse operations. Is this behaviour surprising, or
is there a good reason why there is this large performance difference?
Thanks,
John

from	time	import	time

def	test():
	time_reverse	=0.0
	time_insert	=0.0

	for	lindx	in	xrange(100):
		tmp1		=[]
		time_reverse	-=time()
		for	indx	in	xrange(10000):
			tmp1.append(indx)
		tmp1.reverse()
		time_reverse	+=time()

		tmp2		=[]
		time_insert	-=time()
		for	indx	in	xrange(10000):
			tmp2.insert(0, indx)
		time_insert	+=time()
		assert	tmp1==tmp2
	print	"time_reverse ", time_reverse
	print	"time_insert ", time_insert

test()



More information about the Python-list mailing list