You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

101 lines
2.3 KiB

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <limits.h>
  4. typedef struct {
  5. int id, at, bt, et, tat, wt, rt, used;
  6. } Process;
  7. int proc_cmp(const void *a, const void *b) {
  8. return ((Process*)a)->at - ((Process*)b)->at;
  9. }
  10. int proc_cmp_id(const void *a, const void *b) {
  11. return ((Process*)a)->id - ((Process*)b)->id;
  12. }
  13. int deq(int q[], int *sz) {
  14. int res = q[0];
  15. for (int i = 0; i < *sz-1; ++i) {
  16. q[i] = q[i+1];
  17. }
  18. (*sz)--;
  19. return res;
  20. }
  21. int main() {
  22. int n, mn = INT_MAX, q, qsz = 0;
  23. printf("Quantum: ");
  24. scanf("%d", &q);
  25. printf("Number of processes: ");
  26. scanf("%d", &n);
  27. Process p[n];
  28. int ready[n];
  29. printf("Arrival time and Burst time:\n");
  30. for (int i = 0; i < n; ++i) {
  31. scanf("%d %d", &p[i].at, &p[i].bt);
  32. p[i].id = i;
  33. p[i].et = -1;
  34. p[i].used = 0;
  35. p[i].rt = p[i].bt;
  36. ready[i] = 0;
  37. }
  38. qsort(p, n, sizeof(Process), proc_cmp);
  39. printf("ID\tAT\tBT\tET\tTAT\tWT\n");
  40. double avg_tat = 0, avg_wt = 0;
  41. int curt = 0, jd = 0;
  42. ready[qsz++] = 0;
  43. p[0].used = 1;
  44. while (qsz > 0) {
  45. int id = deq(ready, &qsz);
  46. if (p[id].rt != 0) {
  47. int ex = (p[id].rt < q ? p[id].rt : q);
  48. p[id].rt -= ex;
  49. p[id].et = curt + ex;
  50. curt = p[id].et;
  51. p[id].tat = p[id].et - p[id].at;
  52. p[id].wt = p[id].tat - p[id].bt;
  53. if (p[id].rt == 0) {
  54. avg_tat += p[id].tat;
  55. avg_wt += p[id].wt;
  56. jd++;
  57. }
  58. }
  59. for (int i = 0; i < n; ++i) {
  60. if (curt >= p[i].at && p[i].used == 0) {
  61. ready[qsz++] = i;
  62. p[i].used = 1;
  63. }
  64. }
  65. if (p[id].rt != 0) {
  66. ready[qsz++] = id;
  67. }
  68. if (qsz == 0) {
  69. for (int i = 0; i < n; ++i) {
  70. if (p[i].used == 0) {
  71. ready[qsz++] = i;
  72. p[i].used = 1;
  73. curt = p[i].at;
  74. break;
  75. }
  76. }
  77. }
  78. }
  79. qsort(p, n, sizeof(Process), proc_cmp_id);
  80. for (int i = 0; i < n; ++i) {
  81. printf("%d\t%d\t%d\t%d\t%d\t%d\n", p[i].id, p[i].at, p[i].bt, p[i].et, p[i].tat, p[i].wt);
  82. }
  83. avg_tat /= n;
  84. avg_wt /= n;
  85. printf("avg:\t\t\t\t%lg\t%lg\n", avg_tat, avg_wt);
  86. }