程式排程演算法之先到先服務

tb_youth發表於2020-11-21

程式排程演算法程式排程演算法之先到先服務

先到先服務(First-Come First-Served)

  • 優點:
    編碼簡單且容易理解;
  • 缺點:
    平均等待時間往往很長;

程式碼

根據個人思路模擬的FCFS,僅供參考

#include <iostream>
#include <queue>

using namespace std;
typedef  double TimeType;
const int MAXN =  1e6+5;

int task_num;
TimeType now_time; //從第一個到達的作業時間開始
TimeType avg_spend_time; //平均週轉時間
TimeType avg_weight_time; //平均帶權週轉時間
struct StruTask
{
    int id; //序號
    TimeType arrive_time; //到達時間(輸入)
    TimeType service_time; //服務時間(輸入)
    TimeType start_time; //開始時間(設定)
    TimeType end_time; //結束時間(設定)
    TimeType spend_time; //週轉時間:end_time - arrive_time
    TimeType weight_time; //帶權週轉時間spend_time/service_time

    bool operator< (const StruTask &task)const
    {
        if(arrive_time == task.arrive_time)
            return id > task.id;
        return arrive_time > task.arrive_time;
    }
}arrayTask[MAXN];

priority_queue<StruTask>que;

void get_task()
{
    cout<<"請輸入任務數:"<<endl;
    cin>>task_num;
    if(task_num <= 0) return;
    cout<<"----------請輸入任務相關資訊-------"<<endl;
    for(int i = 1; i <= task_num; ++i)
    {
        cout<<"請輸入第"<<i<<"個任務的 到達時間 和 服務時間:";
        arrayTask[i].id = i;
        cin>>arrayTask[i].arrive_time;
        cin>>arrayTask[i].service_time;
    }
}

int get_next_task()
{
    if(!que.empty())
    {
        StruTask task = que.top();
        que.pop();
        return task.id;
    }
    return 0;

}

void run_task(StruTask &task)
{
    now_time = max(now_time,task.arrive_time);
    task.start_time  = now_time;
    task.end_time = now_time + task.service_time;
    now_time = task.end_time;
    task.spend_time = task.end_time - task.arrive_time;
    avg_spend_time += task.spend_time;
    task.weight_time = task.spend_time / task.service_time;
    avg_weight_time += task.weight_time;
}

void print_result(StruTask &task)
{
    cout<<" id: "<<task.id
        <<" arrive_time: "<<task.arrive_time<<" service: "<<task.service_time;
    cout<<" start: "<<task.start_time<<" end: "<<task.end_time;
    cout<<" spend: "<<task.spend_time<<" weight: "<<task.weight_time<<endl;
}

/*
FCFS:
First-Come First-Served
*/
void FCFS()
{
    for(int i = 1; i <= task_num; ++i)
    {
        que.push(arrayTask[i]);
    }
    now_time = 0;
    avg_spend_time = 0;
    avg_weight_time = 0;
    for(int i = 1; i <= task_num; ++i)
    {
        int id = get_next_task();
        run_task(arrayTask[id]);
        print_result(arrayTask[id]);
    }
}



int main()
{
    get_task();
    FCFS();
    double wait = 0;
    for(int i = 1; i <= task_num; ++i)
    {
        wait += arrayTask[i].start_time - arrayTask[i].arrive_time;
    }
    avg_spend_time /= task_num;
    avg_weight_time /= task_num;
    cout<<" avg_spend: "<<avg_spend_time<<" avg_weight: "<<avg_weight_time<<endl;
    cout<<" avg_wait: "<<(wait/task_num)<<endl;
    return 0;
}

執行示例

3
0 24
0 3
0 3

在這裡插入圖片描述

4
3 2
1 5
6 7
4 3

在這裡插入圖片描述

相關文章