2014-11-14 63 views
0

我目前正在学习数据结构和算法。 我发现Interactive python在打印机模拟python程序中如何计算waittime?

from pythonds.basic.queue import Queue 

import random 

class Printer: 
    def __init__(self, ppm): 
     self.pagerate = ppm 
     self.currentTask = None 
     self.timeRemaining = 0 

    def tick(self): 
     if self.currentTask != None: 
      self.timeRemaining = self.timeRemaining - 1 
      if self.timeRemaining <= 0: 
       self.currentTask = None 

    def busy(self): 
     if self.currentTask != None: 
      return True 
     else: 
      return False 

    def startNext(self,newtask): 
     self.currentTask = newtask 
     self.timeRemaining = newtask.getPages() * 60/self.pagerate 

class Task: 
    def __init__(self,time): 
     self.timestamp = time 
     self.pages = random.randrange(1,21) 

    def getStamp(self): 
     return self.timestamp 

    def getPages(self): 
     return self.pages 

    def waitTime(self, currenttime): 
     return currenttime - self.timestamp 


def simulation(numSeconds, pagesPerMinute): 

    labprinter = Printer(pagesPerMinute) 
    printQueue = Queue() 
    waitingtimes = [] 

    for currentSecond in range(numSeconds): 

     if newPrintTask(): 
     task = Task(currentSecond) 
     printQueue.enqueue(task) 

     if (not labprinter.busy()) and (not printQueue.isEmpty()): 
     nexttask = printQueue.dequeue() 
     waitingtimes.append(nexttask.waitTime(currentSecond)) 
     labprinter.startNext(nexttask) 

     labprinter.tick() 

    averageWait=sum(waitingtimes)/len(waitingtimes) 
    print("Average Wait %6.2f secs %3d tasks remaining."%(averageWait,printQueue.size())) 

def newPrintTask(): 
    num = random.randrange(1,181) 
    if num == 180: 
     return True 
    else: 
     return False 

for i in range(10): 
    simulation(3600,5) 

这段代码可以请别人解释怎样的waitingtimes.append(nexttask.waitTime(currentSecond))计算waitime为currentsecond。 对于那个特定的currentsecond,它不会为零。 同样根据模拟,每180秒有一个新的任务,但它在同一个当前的秒中被排队和出队。 因此,printqueue在任何特定的时间总是空的,还是它?

请帮助...

回答

1

每一秒,有一个随机的机会将任务添加到队列。只有当打印机可用not labprinter.busy()为真)时,才会从队列中取出发送到打印机的任务。

一旦任务被添加到打印机,它将使打印机达到一定数量的滴答('秒')来处理分配给每个任务的随机数量的页面。没有新的任务可以发送给它!调用每个循环迭代labprinter.tick(),其递减self.timeRemaining(基于任务大小和打印机页面速率计算)。只有当该数字达到0时,任务才会被清除,并且打印机不再忙(准备好接受另一项任务)。

所以当打印机忙时队列可能已经满了。在队列中花费几轮循环的任务将等待累积时间。

你可以写下蜱;可以说,它可以处理20页每分钟,所以它会需要3每秒页:

  • 0什么也没有发生

  • 1.创建大小为10的任务。打印机是免费的,所以它会采取任务。 10页需要30秒。

  • 2 - 5.没有创建新任务,打印机打印1页。

  • 6 - 9.一个新的任务创建在时间点8,添加到队列中。打印机打印第2页。

  • 9 - 30.可以创建更多任务,打印机打印其余页面。

  • 31.打印机是免费的,现在可以处理在打勾8创建的任务。该任务等待31 - 8 == 23秒。

+0

谢谢,这是一个明确的解释...非常感谢! – 2014-11-15 13:11:54