python学习之打印机

1、创建打印任务类

import random

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

2、创建打印机类

from queue import Queue


class Printer:
    def __init__(self, speed):
        self.speed = speed
        self.currentTask = None
        self.timeRemaining = 0
        self.queue = Queue()
        self.waitTimes = []

    def isBusy(self):
        return self.currentTask != None

    def tick(self, currentTime):
        if self.currentTask != None:
            self.timeRemaining = self.timeRemaining - 1
            if self.timeRemaining <= 0:
                self.currentTask = None
        elif self.queue.size() > 0:
            self.currentTask = self.queue.dequeue()
            self.waitTimes.append(self.currentTask.waitTime(currentTime))
            self.timeRemaining = self.currentTask.getPages() * 60 / self.speed

    def addTask(self, task):
        self.queue.enqueue(task)

    def getWaitTimes(self):
        return self.waitTimes

3、测试类

import random
from task import Task
from printer import Printer


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


def simulation(testSeconds, speed):
    test_printer = Printer(speed)
    for i in range(testSeconds):
        if newPrinterTask():
            newTask = Task(i)
            test_printer.addTask(newTask)
            execTime = newTask.getPages() * 60 / speed
            print("%s====new task有%s页 执行需要%s"%(i, newTask.getPages(),execTime))
        test_printer.tick(i)

    print(test_printer.getWaitTimes())


simulation(3600, 5)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值