def run(sort_target, segment_count):
    print('========SJF========')
    print('input                : ', sort_target)
    sjf = SJF(sort_target, segment_count)
    print('result               : ', sjf.merge_sub_lists())
    print('cpu burst time       : ', sjf.get_cpu_burst_time())
    print('average waiting time : ', sjf.get_total_waiting_time())

    print('========FCFS=======')
    print('input                : ', sort_target)
    fcfs = FCFS(sort_target, segment_count)
    print('result               : ', fcfs.merge_sub_lists())
    print('cpu burst time       : ', fcfs.get_cpu_burst_time())
    print('average waiting time : ', fcfs.get_total_waiting_time())
示例#2
0
 def get_algorithm(algorithm_name, num_nodes, log_df, epoch_start,
                   epoch_end):
     if algorithm_name == 'fcfs':
         return FCFS(num_nodes, log_df, epoch_start, epoch_end)
     elif algorithm_name == 'rr':
         return RR(num_nodes, log_df, epoch_start, epoch_end)
     else:
         raise RuntimeError("Unknown algorithm {}!".format(algorithm_name))
示例#3
0
def test(process_input_list, cpu_count):
    scheduler_list = []
    scheduler_list.append(FCFS(process_input_list, cpu_count))
    # scheduler_list.append(RR(process_input_list, cpu_count, 2))  # quantum = 2
    # scheduler_list.append(RR(process_input_list, cpu_count, 3))  # quantum = 3
    # scheduler_list.append(HRRN(process_input_list, cpu_count))
    # ...
    for test_idx, scheduler in enumerate(scheduler_list):
        print(
            "[ TEST {0} - {1} - CPU 개수: {2}]======================================="
            .format(test_idx + 1,
                    type(scheduler).__name__, scheduler.cpu_count))
        scheduler.run()
        print_process_time_table(scheduler.processes)
        print_history(scheduler.history)
示例#4
0
def simulateArrivals(option):
    """Powers the simulation"""
    simulateAdding = loadFromFile()
    simulateAdding.sort(key=getKey)
    ready = None

    if option == 1:
        ready = FCFS()
    elif option == 2:
        ready = Priority()
    elif option == 3:
        q = 2
        try:
            q = int(input("Enter Quantum (Defauult=2):"))
        except:
            print("Invalid entry. Using default Quantum of 2.")
            pass
        ready = RoundRobin(q)
    elif option == 4:
        runAllQueues()
        return
    elif option == 5:
        exit(1)
    else:
        print("Invalid option.")
        return

    print("\r")
    print("***************************************************")
    print("Running %s Scheduler" % ready.type)

    remainingQueueSize = 0
    while len(simulateAdding) > 0 or remainingQueueSize > 0:
        for k in simulateAdding[:]:
            if k.simArrival <= ready.times.step:
                try:
                    ready.add(
                        PCB(k.pid,
                            simArrival=k.simArrival,
                            simBurst=k.simBurst,
                            priority=k.priority))
                except Exception as e:
                    print(e)
                simulateAdding.remove(k)

        print("Current Queue:")
        ready.show()
        remainingQueueSize = ready.runNew()

    ready.finishQueue()
    ready.printQueueSimStats(ready.type)
示例#5
0
import random
from fcfs import FCFS
from sstf import SSTF
from scan import SCAN

requests = [random.randrange(500) for i in range(20)]
print(f"Requests: {requests}")
head = int(input("What's the current position of the disk head? "))

fcfs_head_movements, fcfs_head_traversal = FCFS(requests, head)
print("FCFS\n====")
print(f"Total head movements: {fcfs_head_movements}")
print(f"Head traversal: {fcfs_head_traversal}")

sstf_head_movements, sstf_head_traversal = SSTF(requests, head)
print("\nSSTF\n====")
print(f"Total head movements: {sstf_head_movements}")
print(f"Head traversal: {sstf_head_traversal}")

scan_head_movements, scan_head_traversal = SCAN(requests, head)
print("\nSCAN\n====")
print(f"Total head movements: {scan_head_movements}")
print(f"Head traversal: {scan_head_traversal}")
    def run_algorithm(self):
        # 아직 알고리즘 구분 안넣고 RR을 시험삼아 돌림, 그래서 Quantum설정 하려면 RR선택하고 돌려볼것

        # 수정 : 알고리즘 선택하는 부분
        # 한번 설정한 프로세스 목록을 계속해서 돌릴 상황을 가정해야하기 떄문에 깊은 복사로 proc_copy_list에 가져와서 실행
        proc_copy_list = copy.deepcopy(self.proc_list)
        if self.cur_algo == "FCFS":
            scheduler = FCFS(proc_copy_list, int(self.cpu_count.currentText()))
        elif self.cur_algo == "RR":
            scheduler = RR(proc_copy_list, int(self.cpu_count.currentText()), self.tq.value())
        elif self.cur_algo == "SPN":
            scheduler = SPN(proc_copy_list, int(self.cpu_count.currentText()))
        elif self.cur_algo == "SRTN":
            scheduler = SRTN(proc_copy_list, int(self.cpu_count.currentText()))
        elif self.cur_algo == "HRRN":
            scheduler = HRRN(proc_copy_list, int(self.cpu_count.currentText()))
        elif self.cur_algo == "YOSA":
            scheduler = YOSA(proc_copy_list, int(self.cpu_count.currentText()), self.tq.value())

        scheduler.run()
        self.history_slider.setEnabled(True)
        # 실행 이후 히스토리를 self.history에 저장
        # 이후 함수들은 0초를 기준으로 화면에 띄우는것, slider_control과 거이 동일하기 때문에 거기에 주석을 달겠습니다.

        if self.cur_algo != "YOSA":
            self.history = scheduler.history
            # len(self.history) = 경과 시간, 경과 시간을 탐색할 수 있게 슬라이더를 활성화하고 슬라이더의 범위 지정, 초기는 0초
            self.history_slider.setRange(0, len(self.history) - 1)
            self.history_slider.setValue(0)
            self.ready_table.setColumnCount(len(self.history[0][0]))
            self.gantt_table.setColumnCount(0)
            self.result_table.setRowCount(len(self.history[0][2]))

            for q_proc_idx, q_process in enumerate(self.history[0][0]):
                self.ready_table.setItem(0, q_proc_idx, QTableWidgetItem(q_process.id))
                self.ready_table.item(0, q_proc_idx).setBackground(
                    QtGui.QColor(
                        q_process.color[0],
                        q_process.color[1],
                        q_process.color[2],
                    )
                )
            # DEBUG
            # print("queue:", self.history[0][0][queue_process_idx].id)
            for proc_idx, process in enumerate(self.history[0][2]):
                self.result_table.setItem(proc_idx, 0, QTableWidgetItem(process.id))
                self.result_table.setItem(proc_idx, 1, QTableWidgetItem(str(process.at)))
                self.result_table.setItem(proc_idx, 2, QTableWidgetItem(str(process.bt)))
                self.result_table.setItem(proc_idx, 3, QTableWidgetItem(str(process.wt)))
                self.result_table.setItem(proc_idx, 4, QTableWidgetItem(str(process.tt)))
                self.result_table.setItem(proc_idx, 5, QTableWidgetItem(str(process.ntt)))
                self.result_table.item(proc_idx, 0).setBackground(
                    QtGui.QColor(
                        process.color[0],
                        process.color[1],
                        process.color[2],
                    )
                )

        else:
            self.history = scheduler.each_student_history_list
            self.history_slider.setRange(0, 24)
            self.history_slider.setValue(0)
            for student_idx, student in enumerate(scheduler.students):
                # 공부시간
                self.result_table.setItem(student_idx, 0, QTableWidgetItem(str(student.best_solo_total_study_time)))
                # 각 과목 당 공부 시간
                for subject in range(len(student.best_solo_subjects_grade)):
                    self.result_table.setItem(
                        student_idx,
                        1 + subject * 2,
                        QTableWidgetItem(str(student.best_solo_subject_study_case[subject])),
                    )
                    self.result_table.setItem(
                        student_idx,
                        2 + subject * 2,
                        QTableWidgetItem(str(round(student.best_solo_subjects_grade[subject], 2))),
                    )
                # 개인 투자시간이 0인 경우에 결과창에 과목 당 투자 시간 및 학점이 안적히는 문제 수정
                if len(student.best_solo_subjects_grade) == 0:
                    for subject_idx in range(len(student.subject_list)):
                        self.result_table.setItem(
                            student_idx,
                            1 + subject_idx * 2,
                            QTableWidgetItem(str(0)),
                        )
                        self.result_table.setItem(student_idx, 2 + subject_idx * 2, QTableWidgetItem(str(0)))
                self.result_table.setItem(student_idx, 9, QTableWidgetItem(str(student.best_each_team_play_time)))
                self.result_table.setItem(student_idx, 11, QTableWidgetItem(str(round(student.best_avg_grade, 2))))

            # 팀플 학점과 전체 평균은 병합했기에 한번만 입력하면 될 것이라 생각
            self.result_table.setItem(
                0, 10, QTableWidgetItem(str(round(scheduler.students[0].best_team_play_grade, 2)))
            )
            self.result_table.setItem(0, 12, QTableWidgetItem(str(round(scheduler.team_avg_grade, 2))))
            self.ready_table.setDisabled(True)
示例#7
0
            print(i)

    # print_tasks()

    with open('simout.txt', 'w') as out_file:
        ## Now we have the processes, let's go

        ## Always remember the sequence! when out_file!
        ## name, AVG CPU Burst Time, Average Wait Time
        ## Average TurnAround Time, # of context switches
        ## # of preemptions, CPU utilization %
        ## Also, **copy the processes**

        ## Look, here comes the FCFS Algo!
        print_processes()
        fcfs_algo = FCFS(deepcopy(processes), ctx_time)
        avg_cpu_burst, avg_wait, avg_turnaround, num_context_switch, cpu_utilization = fcfs_algo.run(
        )
        out_file.write(
            output_template.format("FCFS", avg_cpu_burst, avg_wait,
                                   avg_turnaround, num_context_switch, 0,
                                   cpu_utilization))

        ### SJF
        print()
        # print_processes() ** controlled by method run **
        sjf_algo = SJF(deepcopy(processes), ctx_time, alpha, lamb)
        avg_cpu_burst, avg_wait, avg_turnaround, num_context_switch, _, cpu_utilization = sjf_algo.run(
        )
        out_file.write(
            output_template.format("SJF", avg_cpu_burst, avg_wait,
示例#8
0
def firstcomefirstserve(preprocessed_data):
    alg = FCFS(preprocessed_data)
    alg.sort_arrival()
    alg.waiting_time()
    alg.turn_around_time()
    alg.save_data()
    alg.output_data()