Bez popisu
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.

mlfq.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. #! /usr/bin/env python
  2. import sys
  3. from optparse import OptionParser
  4. import random
  5. # finds the highest nonempty queue
  6. # -1 if they are all empty
  7. def FindQueue():
  8. q = hiQueue
  9. while q > 0:
  10. if len(queue[q]) > 0:
  11. return q
  12. q -= 1
  13. if len(queue[0]) > 0:
  14. return 0
  15. return -1
  16. def LowerQueue(currJob, currQueue, issuedIO):
  17. if currQueue > 0:
  18. # in this case, have to change the priority of the job
  19. job[currJob]['currPri'] = currQueue - 1
  20. if issuedIO == False:
  21. queue[currQueue-1].append(currJob)
  22. job[currJob]['ticksLeft'] = quantum[currQueue-1]
  23. else:
  24. if issuedIO == False:
  25. queue[currQueue].append(currJob)
  26. job[currJob]['ticksLeft'] = quantum[currQueue]
  27. def Abort(str):
  28. sys.stderr.write(str + '\n')
  29. exit(1)
  30. #
  31. # PARSE ARGUMENTS
  32. #
  33. parser = OptionParser()
  34. parser.add_option('-s', '--seed', help='the random seed',
  35. default=0, action='store', type='int', dest='seed')
  36. parser.add_option('-n', '--numQueues',
  37. help='number of queues in MLFQ (if not using -Q)',
  38. default=3, action='store', type='int', dest='numQueues')
  39. parser.add_option('-q', '--quantum', help='length of time slice (if not using -Q)',
  40. default=10, action='store', type='int', dest='quantum')
  41. parser.add_option('-Q', '--quantumList',
  42. help='length of time slice per queue level, specified as ' + \
  43. 'x,y,z,... where x is the quantum length for the highest ' + \
  44. 'priority queue, y the next highest, and so forth',
  45. default='', action='store', type='string', dest='quantumList')
  46. parser.add_option('-j', '--numJobs', default=3, help='number of jobs in the system',
  47. action='store', type='int', dest='numJobs')
  48. parser.add_option('-m', '--maxlen', default=100, help='max run-time of a job ' +
  49. '(if randomly generating)', action='store', type='int',
  50. dest='maxlen')
  51. parser.add_option('-M', '--maxio', default=10,
  52. help='max I/O frequency of a job (if randomly generating)',
  53. action='store', type='int', dest='maxio')
  54. parser.add_option('-B', '--boost', default=0,
  55. help='how often to boost the priority of all jobs back to ' +
  56. 'high priority', action='store', type='int', dest='boost')
  57. parser.add_option('-i', '--iotime', default=5,
  58. help='how long an I/O should last (fixed constant)',
  59. action='store', type='int', dest='ioTime')
  60. parser.add_option('-S', '--stay', default=False,
  61. help='reset and stay at same priority level when issuing I/O',
  62. action='store_true', dest='stay')
  63. parser.add_option('-I', '--iobump', default=False,
  64. help='if specified, jobs that finished I/O move immediately ' + \
  65. 'to front of current queue',
  66. action='store_true', dest='iobump')
  67. parser.add_option('-l', '--jlist', default='',
  68. help='a comma-separated list of jobs to run, in the form ' + \
  69. 'x1,y1,z1:x2,y2,z2:... where x is start time, y is run ' + \
  70. 'time, and z is how often the job issues an I/O request',
  71. action='store', type='string', dest='jlist')
  72. parser.add_option('-c', help='compute answers for me', action='store_true',
  73. default=False, dest='solve')
  74. (options, args) = parser.parse_args()
  75. random.seed(options.seed)
  76. # MLFQ: How Many Queues
  77. numQueues = options.numQueues
  78. quantum = {}
  79. if options.quantumList != '':
  80. # instead, extract number of queues and their time slic
  81. quantumLengths = options.quantumList.split(',')
  82. numQueues = len(quantumLengths)
  83. qc = numQueues - 1
  84. for i in range(numQueues):
  85. quantum[qc] = int(quantumLengths[i])
  86. qc -= 1
  87. else:
  88. for i in range(numQueues):
  89. quantum[i] = int(options.quantum)
  90. hiQueue = numQueues - 1
  91. # MLFQ: I/O Model
  92. # the time for each IO: not great to have a single fixed time but...
  93. ioTime = int(options.ioTime)
  94. # This tracks when IOs and other interrupts are complete
  95. ioDone = {}
  96. # This stores all info about the jobs
  97. job = {}
  98. # seed the random generator
  99. random.seed(options.seed)
  100. # jlist 'startTime,runTime,ioFreq:startTime,runTime,ioFreq:...'
  101. jobCnt = 0
  102. if options.jlist != '':
  103. allJobs = options.jlist.split(':')
  104. for j in allJobs:
  105. jobInfo = j.split(',')
  106. if len(jobInfo) != 3:
  107. sys.stderr.write('Badly formatted job string. Should be x1,y1,z1:x2,y2,z2:...\n')
  108. sys.stderr.write('where x is the startTime, y is the runTime, and z is the I/O frequency.\n')
  109. exit(1)
  110. assert(len(jobInfo) == 3)
  111. startTime = int(jobInfo[0])
  112. runTime = int(jobInfo[1])
  113. ioFreq = int(jobInfo[2])
  114. job[jobCnt] = {'currPri':hiQueue, 'ticksLeft':quantum[hiQueue], 'startTime':startTime,
  115. 'runTime':runTime, 'timeLeft':runTime, 'ioFreq':ioFreq, 'doingIO':False,
  116. 'firstRun':-1}
  117. if startTime not in ioDone:
  118. ioDone[startTime] = []
  119. ioDone[startTime].append((jobCnt, 'JOB BEGINS'))
  120. jobCnt += 1
  121. else:
  122. # do something random
  123. for j in range(options.numJobs):
  124. startTime = 0
  125. # runTime = int(random.random() * options.maxlen)
  126. # ioFreq = int(random.random() * options.maxio)
  127. runTime = int(random.random() * (options.maxlen - 1) + 1)
  128. ioFreq = int(random.random() * (options.maxio - 1) + 1)
  129. job[jobCnt] = {'currPri':hiQueue, 'ticksLeft':quantum[hiQueue], 'startTime':startTime,
  130. 'runTime':runTime, 'timeLeft':runTime, 'ioFreq':ioFreq, 'doingIO':False,
  131. 'firstRun':-1}
  132. if startTime not in ioDone:
  133. ioDone[startTime] = []
  134. ioDone[startTime].append((jobCnt, 'JOB BEGINS'))
  135. jobCnt += 1
  136. numJobs = len(job)
  137. print 'Here is the list of inputs:'
  138. print 'OPTIONS jobs', numJobs
  139. print 'OPTIONS queues', numQueues
  140. for i in range(len(quantum)-1,-1,-1):
  141. print 'OPTIONS quantum length for queue %2d is %3d' % (i, quantum[i])
  142. print 'OPTIONS boost', options.boost
  143. print 'OPTIONS ioTime', options.ioTime
  144. print 'OPTIONS stayAfterIO', options.stay
  145. print 'OPTIONS iobump', options.iobump
  146. print '\n'
  147. print 'For each job, three defining characteristics are given:'
  148. print ' startTime : at what time does the job enter the system'
  149. print ' runTime : the total CPU time needed by the job to finish'
  150. print ' ioFreq : every ioFreq time units, the job issues an I/O'
  151. print ' (the I/O takes ioTime units to complete)\n'
  152. print 'Job List:'
  153. for i in range(numJobs):
  154. print ' Job %2d: startTime %3d - runTime %3d - ioFreq %3d' % (i, job[i]['startTime'],
  155. job[i]['runTime'], job[i]['ioFreq'])
  156. print ''
  157. if options.solve == False:
  158. print 'Compute the execution trace for the given workloads.'
  159. print 'If you would like, also compute the response and turnaround'
  160. print 'times for each of the jobs.'
  161. print ''
  162. print 'Use the -c flag to get the exact results when you are finished.\n'
  163. exit(0)
  164. # initialize the MLFQ queues
  165. queue = {}
  166. for q in range(numQueues):
  167. queue[q] = []
  168. # TIME IS CENTRAL
  169. currTime = 0
  170. # use these to know when we're finished
  171. totalJobs = len(job)
  172. finishedJobs = 0
  173. print '\nExecution Trace:\n'
  174. while finishedJobs < totalJobs:
  175. # find highest priority job
  176. # run it until either
  177. # (a) the job uses up its time quantum
  178. # (b) the job performs an I/O
  179. # check for priority boost
  180. if options.boost > 0 and currTime != 0:
  181. if currTime % options.boost == 0:
  182. print '[ time %d ] BOOST ( every %d )' % (currTime, options.boost)
  183. # remove all jobs from queues (except high queue)
  184. for q in range(numQueues-1):
  185. for j in queue[q]:
  186. if job[j]['doingIO'] == False:
  187. queue[hiQueue].append(j)
  188. queue[q] = []
  189. # print 'BOOST: QUEUES look like:', queue
  190. # change priority to high priority
  191. # reset number of ticks left for all jobs (XXX just for lower jobs?)
  192. # add to highest run queue (if not doing I/O)
  193. for j in range(numJobs):
  194. # print '-> Boost %d (timeLeft %d)' % (j, job[j]['timeLeft'])
  195. if job[j]['timeLeft'] > 0:
  196. # print '-> FinalBoost %d (timeLeft %d)' % (j, job[j]['timeLeft'])
  197. job[j]['currPri'] = hiQueue
  198. job[j]['ticksLeft'] = quantum[hiQueue]
  199. # print 'BOOST END: QUEUES look like:', queue
  200. # check for any I/Os done
  201. if currTime in ioDone:
  202. for (j, type) in ioDone[currTime]:
  203. q = job[j]['currPri']
  204. job[j]['doingIO'] = False
  205. print '[ time %d ] %s by JOB %d' % (currTime, type, j)
  206. if options.iobump == False or type == 'JOB BEGINS':
  207. queue[q].append(j)
  208. else:
  209. queue[q].insert(0, j)
  210. # now find the highest priority job
  211. currQueue = FindQueue()
  212. if currQueue == -1:
  213. print '[ time %d ] IDLE' % (currTime)
  214. currTime += 1
  215. continue
  216. #print 'FOUND QUEUE: %d' % currQueue
  217. #print 'ALL QUEUES:', queue
  218. # there was at least one runnable job, and hence ...
  219. currJob = queue[currQueue][0]
  220. if job[currJob]['currPri'] != currQueue:
  221. Abort('currPri[%d] does not match currQueue[%d]' % (job[currJob]['currPri'], currQueue))
  222. job[currJob]['timeLeft'] -= 1
  223. job[currJob]['ticksLeft'] -= 1
  224. if job[currJob]['firstRun'] == -1:
  225. job[currJob]['firstRun'] = currTime
  226. runTime = job[currJob]['runTime']
  227. ioFreq = job[currJob]['ioFreq']
  228. ticksLeft = job[currJob]['ticksLeft']
  229. timeLeft = job[currJob]['timeLeft']
  230. print '[ time %d ] Run JOB %d at PRIORITY %d [ TICKSLEFT %d RUNTIME %d TIMELEFT %d ]' % \
  231. (currTime, currJob, currQueue, ticksLeft, runTime, timeLeft)
  232. if timeLeft < 0:
  233. Abort('Error: should never have less than 0 time left to run')
  234. # UPDATE TIME
  235. currTime += 1
  236. # CHECK FOR JOB ENDING
  237. if timeLeft == 0:
  238. print '[ time %d ] FINISHED JOB %d' % (currTime, currJob)
  239. finishedJobs += 1
  240. job[currJob]['endTime'] = currTime
  241. # print 'BEFORE POP', queue
  242. done = queue[currQueue].pop(0)
  243. # print 'AFTER POP', queue
  244. assert(done == currJob)
  245. continue
  246. # CHECK FOR IO
  247. issuedIO = False
  248. if ioFreq > 0 and (((runTime - timeLeft) % ioFreq) == 0):
  249. # time for an IO!
  250. print '[ time %d ] IO_START by JOB %d' % (currTime, currJob)
  251. issuedIO = True
  252. desched = queue[currQueue].pop(0)
  253. assert(desched == currJob)
  254. job[currJob]['doingIO'] = True
  255. # this does the bad rule -- reset your tick counter if you stay at the same level
  256. if options.stay == True:
  257. job[currJob]['ticksLeft'] = quantum[currQueue]
  258. # add to IO Queue: but which queue?
  259. futureTime = currTime + ioTime
  260. if futureTime not in ioDone:
  261. ioDone[futureTime] = []
  262. print 'IO DONE'
  263. ioDone[futureTime].append((currJob, 'IO_DONE'))
  264. # print 'NEW IO EVENT at ', futureTime, ' is ', ioDone[futureTime]
  265. # CHECK FOR QUANTUM ENDING AT THIS LEVEL
  266. if ticksLeft == 0:
  267. # print '--> DESCHEDULE %d' % currJob
  268. if issuedIO == False:
  269. # print '--> BUT IO HAS NOT BEEN ISSUED (therefor pop from queue)'
  270. desched = queue[currQueue].pop(0)
  271. assert(desched == currJob)
  272. # move down one queue! (unless lowest queue)
  273. LowerQueue(currJob, currQueue, issuedIO)
  274. # print out statistics
  275. print ''
  276. print 'Final statistics:'
  277. responseSum = 0
  278. turnaroundSum = 0
  279. for i in range(numJobs):
  280. response = job[i]['firstRun'] - job[i]['startTime']
  281. turnaround = job[i]['endTime'] - job[i]['startTime']
  282. print ' Job %2d: startTime %3d - response %3d - turnaround %3d' % (i, job[i]['startTime'],
  283. response, turnaround)
  284. responseSum += response
  285. turnaroundSum += turnaround
  286. print '\n Avg %2d: startTime n/a - response %.2f - turnaround %.2f' % (i,
  287. float(responseSum)/numJobs,
  288. float(turnaroundSum)/numJobs)
  289. print '\n'