当前位置: 首页 > 知识库问答 >
问题:

Python CPU调度器模拟器

郎同化
2023-03-14

所以我有一个FCFS和SJF CPU模拟器调度算法,但是我正在努力实现最短剩余时间优先算法。

这是我目前掌握的情况。

def srtf(submit_times, burst_times):
    """First Come First Serve Algorithm returns the time metrics"""
    cpu_clock = 0
    job = 0
    response_times = []
    turn_around_times = []
    wait_times = []
    total_jobs = []
    remaining_burst_times = []

    for stuff in range(len(submit_times)):
        total_jobs.append(tuple((submit_times[stuff], burst_times[stuff])))
        remaining_burst_times.append(burst_times[stuff])

    while job < len(submit_times):

        if cpu_clock < int(submit_times[job]):
            cpu_clock = int(submit_times[job])

        ready_queue = []
        for the_job in total_jobs:
            job_time = int(the_job[0])
            if job_time <= cpu_clock:
                ready_queue.append(the_job)

        short_job = ready_queue_bubble(ready_queue)

        submit, burst = short_job[0], short_job[1]

        next_event = cpu_clock + int(burst)

        response_time = cpu_clock - int(submit)
        response_times.append(response_time)

        remaining_burst_times[job] = next_event - cpu_clock

        # cpu_clock = next_event
        if remaining_burst_times[job] == 0:
            turn_around_time = next_event - int(submit)
            wait_time = turn_around_time - int(burst)
            turn_around_times.append(turn_around_time)
            wait_times.append(wait_time)
        else:
            pass

        job += 1
        total_jobs.remove(short_job)
        remaining_burst_times.remove(short_job[1])

    return response_times, turn_around_times, wait_times

基本上,该函数接收提交时间和突发时间的列表,并返回响应、转身和等待时间的列表。我一直试图先用就绪队列编辑我短暂工作的残余,但没有成功。

有人能给我指一下正确的方向吗?

共有1个答案

邓昊天
2023-03-14

由于抢占,这不是一个非常简单的模拟。设计模拟就是要表示 1) 世界状态和 2) 作用于世界的事件。

这里的世界状况是:

>

  • 过程。它们有自己的内部状态。

    • 提交时间(不可变)
    • 突发时间(不可变)
    • 剩余时间(可变)
    • 完成时间(可变)

    挂钟时间。

    下一个要提交的过程。

    正在运行进程。

    运行开始时间(当前运行的进程)。

    等待可运行流程(即,已提交但剩余

    只有两种事件。

    • 进程的提交时间发生。
    • 运行过程完成。

    当没有更多的进程等待提交,并且没有进程正在运行时,模拟就结束了。您可以从流程中获取所需的统计信息。

    算法初始化状态,然后执行标准事件循环:

    processes = list of Process built from parameters, sorted by submit time
    wall_clock = 0
    next_submit = 0 # index in list of processes
    running = None # index of running process
    run_start = None # start of current run
    waiting = []
    while True:
       event = GetNextEvent()
       if event is None:
         break
       wall_clock = event.time
       if event.kind == 'submit':
         # Update state for new process submission.
       else: # event.kind is 'completion'
         # Update state for running process completion.
    

    一个重要的细节是,如果完成和提交事件同时发生,请先处理完成。另一种方式'round使更新逻辑变得复杂;剩余时间为零的正在运行的进程是一种特殊情况。

    “更新状态”方法根据srtf算法调整状态的所有元素。大致像这样…

    def UpdateStateForProcessCompletion():
      # End the run of the running process
      processes[running].remaining = 0
      processes[running].completion_time = wall_clock
    
      # Schedule a new one, if any are waiting.
      running = PopShortestTimeRemainingProcess(waiting)
      run_start_time = clock_time if running else None
    

    新提交更复杂。

    def UpdateStateForProcessCompletion():
      new_process = next_submit
      next_submit += 1
      new_time_remaining = processes[new_process].remaining
    
      # Maybe preempt the running process.
      if running:
        # Get updated remaining time to run.
        running_time_remaining = processes[running].remaining - (wall_clock - run_start)
        # We only need to look at new and running processes. 
        # Waiting ones can't win because they already lost to the running one.
        if new_time_remaining < running_time_remaining:
          # Preempt.
          processes[running].remaining = running_time_remaining
          waiting.append(running)
          running = new_process
          run_start_time = wall_clock
        else:
          # New process waits. Nothing else changes
          waiting.append(new_process)
      else:
        # Nothing's running. Run the newly submitted process.
        running = new_process
        run_start_time = wall_clock
    

    唯一剩下的就是获取下一个事件。您只需要检查进程[next_submit]。提交wall_clock进程[运行]。剩余。选择最小的。事件有那个时间和相应的类型。当然,您需要处理next_submit和/或运行的情况。

    我这里可能没有完美的一切,但已经很接近了。

    添加

    希望你在这个时候完成你的家庭作业。这很有趣。我在此示例上运行了它,跟踪匹配良好。干杯

    import heapq as pq
    
    class Process(object):
      """A description of a process in the system."""
      def __init__(self, id, submit, burst):
        self.id = id
        self.submit = submit
        self.burst = burst
        self.remaining = burst
        self.completion = None
        self.first_run = None
    
      @property
      def response(self):
        return None if self.first_run is None else self.first_run - self.submit
    
      @property
      def turnaround(self):
        return None if self.completion is None else self.completion - self.submit
    
      @property
      def wait(self):
        return None if self.turnaround is None else self.turnaround - self.burst
     
      def __repr__(self):
        return f'P{self.id} @ {self.submit} for {self.burst} ({-self.remaining or self.completion})'
    
    
    def srtf(submits, bursts):
      # Make a list of processes in submit time order.
      processes = [Process(i + 1, submits[i], bursts[i]) for i in range(len(submits))]
      processes_by_submit_asc = sorted(processes, key=lambda x: x.submit)
      process_iter = iter(processes_by_submit_asc)
      
      # The state of the simulation:
      wall_clock = 0  # Wall clock time.
      next_submit = next(process_iter, None)  # Next process to be submitted.
      running = None  # Running process.
      run_start = None  # Time the running process started running.
      waiting = []  # Heap of waiting processes. Pop gets min remaining.
     
      def run(process):
        """Switch the running process to the given one, which may be None."""
        nonlocal running, run_start
        running = process
        if running is None:
          run_start = None
          return
        running.first_run = running.first_run or wall_clock
        run_start = wall_clock
    
      while next_submit or running:
        print(f'Wall clock: {wall_clock}')
        print(f'Running: {running} since {run_start}')
        print(f'Waiting: {waiting}')
    
        # Handle completion first, if there is one.
        if running and (next_submit is None or run_start + running.remaining <= next_submit.submit):
          print('Complete')
          wall_clock = run_start + running.remaining
          running.remaining = 0
          running.completion = wall_clock
          run(pq.heappop(waiting)[1] if waiting else None)
          continue
    
        # Handle a new submit, if there is one.
        if next_submit and (running is None or next_submit.submit < run_start + running.remaining):
          print(f'Submit: {next_submit}')
          new_process = next_submit
          next_submit = next(process_iter, None)
          wall_clock = new_process.submit
          new_time_remaining = new_process.remaining
          if running:
            # Maybe preempt the running process. Otherwise new process waits.
            running_time_remaining = running.remaining - (wall_clock - run_start)
            if new_time_remaining < running_time_remaining:
              print('Preempt!')
              running.remaining = running_time_remaining
              pq.heappush(waiting, (running_time_remaining, running))
              run(new_process)
            else:
              pq.heappush(waiting, (new_time_remaining, new_process))
          else:
            run(new_process)
    
      for p in processes:
        print(f'{p} {p.response} {p.turnaround} {p.wait}')
    
      return ([p.response for p in processes],
              [p.turnaround for p in processes],
              [p.wait for p in processes])
    
    
    submits = [6,3,4,1,2,5]
    bursts = [1,3,6,5,2,1]
    print(srtf(submits, bursts))
    

  •  类似资料:
    • 我很好奇如何在Java中实现FIFO(先进先出)算法。我已经创建了3个类,但必须实现FIFO和SJF(最短作业优先)的调度算法。 对于模拟器类,我们有以下变量: 那么方法是: 其他方法有: 还有另外两个类进程和CPU。进程保存有关应存储在那里的单个进程的任何信息。

    • 我的iOS应用程序随机崩溃。当internet连接速度慢时,就会发生这种情况。我办公室网速太快了。 为了在模拟器上进行测试,我安装了这里提到的网络链接调理器:安装苹果的网络链接调理器工具 现在的问题是,我选择了一个较慢的连接配置文件,但我仍然拥有模拟器中正常(快速)的互联网速度。 我还创建了自己的配置文件,并将下载带宽设置为5Kbps,但仍然没用。 我有:Mackbook retina,OSX 1

    • 概述 NPU模拟器能够在PC机上模拟NPU硬件行为,使用NPU模拟器,用户可以在缺少硬件环境的情况下,方便地部署和调试模型,验证模型搭建是否正确,测试模型准确率等。 代码获取 NPU模拟器的库和示例代码在我们的阿里云代码服务器上,如果您需要下载权限,请告知我们的FAE,我们会给您释放下载代码的权限。 编译运行 我们同时发布了带有版本信息的动态库libgxdnn.so和静态库libgxdnn.a,您

    • 我知道这是一个常见的问题,但我觉得我已经试过了所有的解决方案,所以我不知道该怎么做了。 已安装Intel x86 HAXM 尝试在SDK管理器中重新安装仿真程序 尝试使用不同API级别的各种AVD 我不明白是怎么回事,在过去的两天里,我对这种情况感到非常沮丧,任何帮助或提示都将不胜感激!

    • Storm 现在有 4 种内置的 schedulers(调度器): DefaultScheduler, IsolationScheduler, MultitenantScheduler, ResourceAwareScheduler. Pluggable scheduler(可插拔的调度器) 你可以实现你自己的 scheduler(调度器)来替换掉默认的 scheduler(调度器),自定义分配e

    • 调度器提供了同步递增策略变化的方法。 它应以手工艺等一致性算法为基础,以确保所有执行者的一致性和一致性。 通过调度器用户们可以轻松地建立分布式集群。 调度器的方法分为两部分。 第一种是与Casbin相结合的方法。 这些方法应该在Casbin内部调用。 用户们可以使用由Casbin本身提供的更完整的api。 另一个部分是调度器本身定义的方法,包括调度器初始化方法, 和不同算法提供的不同函数,如动态资