I have implemented push and pop functions in queue using following methods.
- Initialise list as [], push:list.append(), pop:list.pop(0)
- Initialise list as [None]*100,front=rear=0, push: list[rear]=item, rear++, pop: front++ (while incrementing front or rear, it is doing x = (x+1)%100).
I was expecting, the second approach will be faster, because pop in second approach just increments the front counter, and pop in first approach has to shift all list items to an index lower, e.g. from list1 to list[0], from list[2] to list1 etc.
But my experiment with timeit() shows the 1st approach is faster. Can anyone explain why?
code:
def initialiseQueue():
global L,Ld,front,rear,size
L=[None]*100
Ld=[]
front=0
rear=0
size = 100
def enqueue(x):
global L, rear, size
if (rear+1)%size==front: # full
print("Queue is full. Can't add new item.")
return 1
else:
L[rear] = x
rear = (rear +1)%size
return 0
def dequeue():
global L, front,rear, size
if front==rear: #empty
print("Queue is empty")
else:
x = L[front]
front = (front + 1)%size
return x
from random import *
def qDQ(m,n,way='default'):
for _ in range(m):
for i in range(n):
x = randint(1,10)
addToQueue(x,way)
for i in range(n):
removefromQueue(way)
def addToQueue(x,way):
global L,Ld
if way == 'default':
Ld.append(x)
else:
enqueue(x)
def removefromQueue(way):
global L,Ld
if way == 'default':
return Ld.pop(0)
else:
return dequeue()
from time import *
from timeit import *
m,n=input("Enter two integers separated with spaces:").split(" ")
m=int(m)
n=int(n)
a = timeit(stmt="qDQ(m,n,'default')",setup='initialiseQueue()',timer=process_time,number=10000, globals=globals())
b = timeit(stmt="qDQ(m,n,'special')",setup='initialiseQueue()',timer=process_time,number=10000, globals=globals())
print("Process time for add/remove from queue using list built-in functions:",a)
print("Process time for add/remove from queue using approach 2:",b)
print("Hence","approach 1" if a<b else "approach 2","is faster!")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…