操作系统导论-py2文件修改为py3文件快捷解决方法

在操作系统导论作业中,我们需要用到HW文件。但是这个代码包中,所有.py文件都是py2格式的,需要我们修改为py3文件后运行,即将.py文件开头的

#! /usr/bin/env python

修改为:

#! /usr/bin/env python3

在前面小部分文件中,这样就解决问题了。但后续的大部分文件,包含了大量的print语句。众所周知,py2和py3的print语句格式是不一样的,后者比前者多了一个括号()。这时候不少同学就开始手动修改代码,这也不失为一种方法。但是,我们也可以使用一些神奇的库函数修改。

 

比如如下py2代码:

#! /usr/bin/env python

import sys
from optparse import OptionParser
import random

# finds the highest nonempty queue
# -1 if they are all empty
def FindQueue():
    q = hiQueue
    while q > 0:
        if len(queue[q]) > 0:
            return q
        q -= 1
    if len(queue[0]) > 0:
        return 0
    return -1

def Abort(str):
    sys.stderr.write(str + '\n')
    exit(1)


#
# PARSE ARGUMENTS
#

parser = OptionParser()
parser.add_option('-s', '--seed', help='the random seed', 
                  default=0, action='store', type='int', dest='seed')
parser.add_option('-n', '--numQueues',
                  help='number of queues in MLFQ (if not using -Q)', 
                  default=3, action='store', type='int', dest='numQueues')
parser.add_option('-q', '--quantum', help='length of time slice (if not using -Q)',
                  default=10, action='store', type='int', dest='quantum')
parser.add_option('-a', '--allotment', help='length of allotment (if not using -A)',
                  default=1, action='store', type='int', dest='allotment')
parser.add_option('-Q', '--quantumList',
                  help='length of time slice per queue level, specified as ' + \
                  'x,y,z,... where x is the quantum length for the highest ' + \
                  'priority queue, y the next highest, and so forth', 
                  default='', action='store', type='string', dest='quantumList')
parser.add_option('-A', '--allotmentList',
                  help='length of time allotment per queue level, specified as ' + \
                  'x,y,z,... where x is the # of time slices for the highest ' + \
                  'priority queue, y the next highest, and so forth', 
                  default='', action='store', type='string', dest='allotmentList')
parser.add_option('-j', '--numJobs', default=3, help='number of jobs in the system',
                  action='store', type='int', dest='numJobs')
parser.add_option('-m', '--maxlen', default=100, help='max run-time of a job ' +
                  '(if randomly generating)', action='store', type='int',
                  dest='maxlen')
parser.add_option('-M', '--maxio', default=10,
                  help='max I/O frequency of a job (if randomly generating)',
                  action='store', type='int', dest='maxio')
parser.add_option('-B', '--boost', default=0,
                  help='how often to boost the priority of all jobs back to ' +
                  'high priority', action='store', type='int', dest='boost')
parser.add_option('-i', '--iotime', default=5,
                  help='how long an I/O should last (fixed constant)',
                  action='store', type='int', dest='ioTime')
parser.add_option('-S', '--stay', default=False,
                  help='reset and stay at same priority level when issuing I/O',
                  action='store_true', dest='stay')
parser.add_option('-I', '--iobump', default=False,
                  help='if specified, jobs that finished I/O move immediately ' + \
                  'to front of current queue',
                  action='store_true', dest='iobump')
parser.add_option('-l', '--jlist', default='',
                  help='a comma-separated list of jobs to run, in the form ' + \
                  'x1,y1,z1:x2,y2,z2:... where x is start time, y is run ' + \
                  'time, and z is how often the job issues an I/O request',
                  action='store', type='string', dest='jlist')
parser.add_option('-c', help='compute answers for me', action='store_true',
                  default=False, dest='solve')

(options, args) = parser.parse_args()

random.seed(options.seed)

# MLFQ: How Many Queues
numQueues = options.numQueues

quantum = {}
if options.quantumList != '':
    # instead, extract number of queues and their time slic
    quantumLengths = options.quantumList.split(',')
    numQueues = len(quantumLengths)
    qc = numQueues - 1
    for i in range(numQueues):
        quantum[qc] = int(quantumLengths[i])
        qc -= 1
else:
    for i in range(numQueues):
        quantum[i] = int(options.quantum)

allotment = {}
if options.allotmentList != '':
    allotmentLengths = options.allotmentList.split(',')
    if numQueues != len(allotmentLengths):
        print('number of allotments specified must match number of quantums')
        exit(1)
    qc = numQueues - 1
    for i in range(numQueues):
        allotment[qc] = int(allotmentLengths[i])
        if qc != 0 and allotment[qc] <= 0:
            print('allotment must be positive integer')
            exit(1)
        qc -= 1
else:
    for i in range(numQueues):
        allotment[i] = int(options.allotment)

hiQueue = numQueues - 1

# MLFQ: I/O Model
# the time for each IO: not great to have a single fixed time but...
ioTime = int(options.ioTime)

# This tracks when IOs and other interrupts are complete
ioDone = {}

# This stores all info about the jobs
job = {}

# seed the random generator
random.seed(options.seed)

# jlist 'startTime,runTime,ioFreq:startTime,runTime,ioFreq:...'
jobCnt = 0
if options.jlist != '':
    allJobs = options.jlist.split(':')
    for j in allJobs:
        jobInfo = j.split(',')
        if len(jobInfo) != 3:
            print('Badly formatted job string. Should be x1,y1,z1:x2,y2,z2:...')
            print('where x is the startTime, y is the runTime, and z is the I/O frequency.')
            exit(1)
        assert(len(jobInfo) == 3)
        startTime = int(jobInfo[0])
        runTime   = int(jobInfo[1])
        ioFreq    = int(jobInfo[2])
        job[jobCnt] = {'currPri':hiQueue, 'ticksLeft':quantum[hiQueue],
                       'allotLeft':allotment[hiQueue], 'startTime':startTime,
                       'runTime':runTime, 'timeLeft':runTime, 'ioFreq':ioFreq, 'doingIO':False,
                       'firstRun':-1}
        if startTime not in ioDone:
            ioDone[startTime] = []
        ioDone[startTime].append((jobCnt, 'JOB BEGINS'))
        jobCnt += 1
else:
    # do something random
    for j in range(options.numJobs):
        startTime = 0
        runTime   = int(random.random() * (options.maxlen - 1) + 1)
        ioFreq    = int(random.random() * (options.maxio - 1) + 1)
        
        job[jobCnt] = {'currPri':hiQueue, 'ticksLeft':quantum[hiQueue],
                       'allotLeft':allotment[hiQueue], 'startTime':startTime,
                       'runTime':runTime, 'timeLeft':runTime, 'ioFreq':ioFreq, 'doingIO':False,
                       'firstRun':-1}
        if startTime not in ioDone:
            ioDone[startTime] = []
        ioDone[startTime].append((jobCnt, 'JOB BEGINS'))
        jobCnt += 1


numJobs = len(job)

print 'Here is the list of inputs:'
print 'OPTIONS jobs',            numJobs
print 'OPTIONS queues',          numQueues
for i in range(len(quantum)-1,-1,-1):
    print 'OPTIONS allotments for queue %2d is %3d' % (i, allotment[i])
    print 'OPTIONS quantum length for queue %2d is %3d' % (i, quantum[i])
print 'OPTIONS boost',           options.boost
print 'OPTIONS ioTime',          options.ioTime
print 'OPTIONS stayAfterIO',     options.stay
print 'OPTIONS iobump',          options.iobump

print '\n'
print 'For each job, three defining characteristics are given:'
print '  startTime : at what time does the job enter the system'
print '  runTime   : the total CPU time needed by the job to finish'
print '  ioFreq    : every ioFreq time units, the job issues an I/O'
print '              (the I/O takes ioTime units to complete)\n'

print 'Job List:'
for i in range(numJobs):
    print '  Job %2d: startTime %3d - runTime %3d - ioFreq %3d' % (i, job[i]['startTime'],
                                                                   job[i]['runTime'],
                                                                   job[i]['ioFreq'])
print ''

if options.solve == False:
    print 'Compute the execution trace for the given workloads.'
    print 'If you would like, also compute the response and turnaround'
    print 'times for each of the jobs.'
    print ''
    print 'Use the -c flag to get the exact results when you are finished.\n'
    exit(0)

# initialize the MLFQ queues
queue = {}
for q in range(numQueues):
    queue[q] = []

# TIME IS CENTRAL
currTime = 0

# use these to know when we're finished
totalJobs    = len(job)
finishedJobs = 0

print '\nExecution Trace:\n'

while finishedJobs < totalJobs:
    # find highest priority job
    # run it until either
    # (a) the job uses up its time quantum
    # (b) the job performs an I/O

    # check for priority boost
    if options.boost > 0 and currTime != 0:
        if currTime % options.boost == 0:
            print '[ time %d ] BOOST ( every %d )' % (currTime, options.boost)
            # remove all jobs from queues (except high queue) and put them in high queue
            for q in range(numQueues-1):
                for j in queue[q]:
                    if job[j]['doingIO'] == False:
                        queue[hiQueue].append(j)
                queue[q] = []

            # change priority to high priority
            # reset number of ticks left for all jobs (just for lower jobs?)
            # add to highest run queue (if not doing I/O)
            for j in range(numJobs):
                # print '-> Boost %d (timeLeft %d)' % (j, job[j]['timeLeft'])
                if job[j]['timeLeft'] > 0:
                    # print '-> FinalBoost %d (timeLeft %d)' % (j, job[j]['timeLeft'])
                    job[j]['currPri']   = hiQueue
                    job[j]['ticksLeft'] = allotment[hiQueue]
            # print 'BOOST END: QUEUES look like:', queue

    # check for any I/Os done
    if currTime in ioDone:
        for (j, type) in ioDone[currTime]:
            q = job[j]['currPri']
            job[j]['doingIO'] = False
            print '[ time %d ] %s by JOB %d' % (currTime, type, j)
            if options.iobump == False or type == 'JOB BEGINS':
                queue[q].append(j)
            else:
                queue[q].insert(0, j)

    # now find the highest priority job
    currQueue = FindQueue()
    if currQueue == -1:
        print '[ time %d ] IDLE' % (currTime)
        currTime += 1
        continue
            
    # there was at least one runnable job, and hence ...
    currJob = queue[currQueue][0]
    if job[currJob]['currPri'] != currQueue:
        Abort('currPri[%d] does not match currQueue[%d]' % (job[currJob]['currPri'], currQueue))

    job[currJob]['timeLeft']  -= 1
    job[currJob]['ticksLeft'] -= 1

    if job[currJob]['firstRun'] == -1:
        job[currJob]['firstRun'] = currTime

    runTime   = job[currJob]['runTime']
    ioFreq    = job[currJob]['ioFreq']
    ticksLeft = job[currJob]['ticksLeft']
    allotLeft = job[currJob]['allotLeft']
    timeLeft  = job[currJob]['timeLeft']

    print '[ time %d ] Run JOB %d at PRIORITY %d [ TICKS %d ALLOT %d TIME %d (of %d) ]' % \
          (currTime, currJob, currQueue, ticksLeft, allotLeft, timeLeft, runTime)

    if timeLeft < 0:
        Abort('Error: should never have less than 0 time left to run')


    # UPDATE TIME
    currTime += 1

    # CHECK FOR JOB ENDING
    if timeLeft == 0:
        print '[ time %d ] FINISHED JOB %d' % (currTime, currJob)
        finishedJobs += 1
        job[currJob]['endTime'] = currTime
        # print 'BEFORE POP', queue
        done = queue[currQueue].pop(0)
        # print 'AFTER POP', queue
        assert(done == currJob)
        continue

    # CHECK FOR IO
    issuedIO = False
    if ioFreq > 0 and (((runTime - timeLeft) % ioFreq) == 0):
        # time for an IO!
        print '[ time %d ] IO_START by JOB %d' % (currTime, currJob)
        issuedIO = True
        desched = queue[currQueue].pop(0)
        assert(desched == currJob)
        job[currJob]['doingIO'] = True
        # this does the bad rule -- reset your tick counter if you stay at the same level
        if options.stay == True:
            job[currJob]['ticksLeft'] = quantum[currQueue]
            job[currJob]['allotLeft'] = allotment[currQueue]
        # add to IO Queue: but which queue?
        futureTime = currTime + ioTime
        if futureTime not in ioDone:
            ioDone[futureTime] = []
        print 'IO DONE'
        ioDone[futureTime].append((currJob, 'IO_DONE'))
        
    # CHECK FOR QUANTUM ENDING AT THIS LEVEL (BUT REMEMBER, THERE STILL MAY BE ALLOTMENT LEFT)
    if ticksLeft == 0:
        if issuedIO == False:
            # IO HAS NOT BEEN ISSUED (therefor pop from queue)'
            desched = queue[currQueue].pop(0)
        assert(desched == currJob)

        job[currJob]['allotLeft'] = job[currJob]['allotLeft'] - 1

        if job[currJob]['allotLeft'] == 0:
            # this job is DONE at this level, so move on
            if currQueue > 0:
                # in this case, have to change the priority of the job
                job[currJob]['currPri']   = currQueue - 1
                job[currJob]['ticksLeft'] = quantum[currQueue-1]
                job[currJob]['allotLeft'] = allotment[currQueue-1]
                if issuedIO == False:
                    queue[currQueue-1].append(currJob)
            else:
                job[currJob]['ticksLeft'] = quantum[currQueue]
                job[currJob]['allotLeft'] = allotment[currQueue]
                if issuedIO == False:
                    queue[currQueue].append(currJob)
        else:
            # this job has more time at this level, so just push it to end
            job[currJob]['ticksLeft'] = quantum[currQueue]
            if issuedIO == False:
                queue[currQueue].append(currJob)

        


# print out statistics
print ''
print 'Final statistics:'
responseSum   = 0
turnaroundSum = 0
for i in range(numJobs):
    response   = job[i]['firstRun'] - job[i]['startTime']
    turnaround = job[i]['endTime'] - job[i]['startTime']
    print '  Job %2d: startTime %3d - response %3d - turnaround %3d' % (i, job[i]['startTime'],
                                                                        response, turnaround)
    responseSum   += response
    turnaroundSum += turnaround

print '\n  Avg %2d: startTime n/a - response %.2f - turnaround %.2f' % (i, 
                                                                        float(responseSum)/numJobs,
                                                                        float(turnaroundSum)/numJobs)

print '\n'

如果直接在终端运行,不修改print语句的话,会报这种错误:

可以打开Pycharm,把代码全部复制过去(注意选择Ctrl+Alt+Shift+V,即无格式文本粘贴,不然会出现自动换行现象),然后使用2to3命令:

 

如果没安装的uu可以安装一下

pip install 2to3

然后再Pycharm终端输入:

2to3 -w your_script.py

其中,your_script为你的新py文件名称。

新的py3文件就生成好啦!

#! /usr/bin/env python3

import sys
from optparse import OptionParser
import random

# finds the highest nonempty queue
# -1 if they are all empty
def FindQueue():
    q = hiQueue
    while q > 0:
        if len(queue[q]) > 0:
            return q
        q -= 1
    if len(queue[0]) > 0:
        return 0
    return -1

def Abort(str):
    sys.stderr.write(str + '\n')
    exit(1)


#
# PARSE ARGUMENTS
#

parser = OptionParser()
parser.add_option('-s', '--seed', help='the random seed',
                  default=0, action='store', type='int', dest='seed')
parser.add_option('-n', '--numQueues',
                  help='number of queues in MLFQ (if not using -Q)',
                  default=3, action='store', type='int', dest='numQueues')
parser.add_option('-q', '--quantum', help='length of time slice (if not using -Q)',
                  default=10, action='store', type='int', dest='quantum')
parser.add_option('-a', '--allotment', help='length of allotment (if not using -A)',
                  default=1, action='store', type='int', dest='allotment')
parser.add_option('-Q', '--quantumList',
                  help='length of time slice per queue level, specified as ' + \
                  'x,y,z,... where x is the quantum length for the highest ' + \
                  'priority queue, y the next highest, and so forth',
                  default='', action='store', type='string', dest='quantumList')
parser.add_option('-A', '--allotmentList',
                  help='length of time allotment per queue level, specified as ' + \
                  'x,y,z,... where x is the # of time slices for the highest ' + \
                  'priority queue, y the next highest, and so forth',
                  default='', action='store', type='string', dest='allotmentList')
parser.add_option('-j', '--numJobs', default=3, help='number of jobs in the system',
                  action='store', type='int', dest='numJobs')
parser.add_option('-m', '--maxlen', default=100, help='max run-time of a job ' +
                  '(if randomly generating)', action='store', type='int',
                  dest='maxlen')
parser.add_option('-M', '--maxio', default=10,
                  help='max I/O frequency of a job (if randomly generating)',
                  action='store', type='int', dest='maxio')
parser.add_option('-B', '--boost', default=0,
                  help='how often to boost the priority of all jobs back to ' +
                  'high priority', action='store', type='int', dest='boost')
parser.add_option('-i', '--iotime', default=5,
                  help='how long an I/O should last (fixed constant)',
                  action='store', type='int', dest='ioTime')
parser.add_option('-S', '--stay', default=False,
                  help='reset and stay at same priority level when issuing I/O',
                  action='store_true', dest='stay')
parser.add_option('-I', '--iobump', default=False,
                  help='if specified, jobs that finished I/O move immediately ' + \
                  'to front of current queue',
                  action='store_true', dest='iobump')
parser.add_option('-l', '--jlist', default='',
                  help='a comma-separated list of jobs to run, in the form ' + \
                  'x1,y1,z1:x2,y2,z2:... where x is start time, y is run ' + \
                  'time, and z is how often the job issues an I/O request',
                  action='store', type='string', dest='jlist')
parser.add_option('-c', help='compute answers for me', action='store_true',
                  default=False, dest='solve')

(options, args) = parser.parse_args()

random.seed(options.seed)

# MLFQ: How Many Queues
numQueues = options.numQueues

quantum = {}
if options.quantumList != '':
    # instead, extract number of queues and their time slic
    quantumLengths = options.quantumList.split(',')
    numQueues = len(quantumLengths)
    qc = numQueues - 1
    for i in range(numQueues):
        quantum[qc] = int(quantumLengths[i])
        qc -= 1
else:
    for i in range(numQueues):
        quantum[i] = int(options.quantum)

allotment = {}
if options.allotmentList != '':
    allotmentLengths = options.allotmentList.split(',')
    if numQueues != len(allotmentLengths):
        print('number of allotments specified must match number of quantums')
        exit(1)
    qc = numQueues - 1
    for i in range(numQueues):
        allotment[qc] = int(allotmentLengths[i])
        if qc != 0 and allotment[qc] <= 0:
            print('allotment must be positive integer')
            exit(1)
        qc -= 1
else:
    for i in range(numQueues):
        allotment[i] = int(options.allotment)

hiQueue = numQueues - 1

# MLFQ: I/O Model
# the time for each IO: not great to have a single fixed time but...
ioTime = int(options.ioTime)

# This tracks when IOs and other interrupts are complete
ioDone = {}

# This stores all info about the jobs
job = {}

# seed the random generator
random.seed(options.seed)

# jlist 'startTime,runTime,ioFreq:startTime,runTime,ioFreq:...'
jobCnt = 0
if options.jlist != '':
    allJobs = options.jlist.split(':')
    for j in allJobs:
        jobInfo = j.split(',')
        if len(jobInfo) != 3:
            print('Badly formatted job string. Should be x1,y1,z1:x2,y2,z2:...')
            print('where x is the startTime, y is the runTime, and z is the I/O frequency.')
            exit(1)
        assert(len(jobInfo) == 3)
        startTime = int(jobInfo[0])
        runTime   = int(jobInfo[1])
        ioFreq    = int(jobInfo[2])
        job[jobCnt] = {'currPri':hiQueue, 'ticksLeft':quantum[hiQueue],
                       'allotLeft':allotment[hiQueue], 'startTime':startTime,
                       'runTime':runTime, 'timeLeft':runTime, 'ioFreq':ioFreq, 'doingIO':False,
                       'firstRun':-1}
        if startTime not in ioDone:
            ioDone[startTime] = []
        ioDone[startTime].append((jobCnt, 'JOB BEGINS'))
        jobCnt += 1
else:
    # do something random
    for j in range(options.numJobs):
        startTime = 0
        runTime   = int(random.random() * (options.maxlen - 1) + 1)
        ioFreq    = int(random.random() * (options.maxio - 1) + 1)

        job[jobCnt] = {'currPri':hiQueue, 'ticksLeft':quantum[hiQueue],
                       'allotLeft':allotment[hiQueue], 'startTime':startTime,
                       'runTime':runTime, 'timeLeft':runTime, 'ioFreq':ioFreq, 'doingIO':False,
                       'firstRun':-1}
        if startTime not in ioDone:
            ioDone[startTime] = []
        ioDone[startTime].append((jobCnt, 'JOB BEGINS'))
        jobCnt += 1


numJobs = len(job)

print('Here is the list of inputs:')
print('OPTIONS jobs',            numJobs)
print('OPTIONS queues',          numQueues)
for i in range(len(quantum)-1,-1,-1):
    print('OPTIONS allotments for queue %2d is %3d' % (i, allotment[i]))
    print('OPTIONS quantum length for queue %2d is %3d' % (i, quantum[i]))
print('OPTIONS boost',           options.boost)
print('OPTIONS ioTime',          options.ioTime)
print('OPTIONS stayAfterIO',     options.stay)
print('OPTIONS iobump',          options.iobump)

print('\n')
print('For each job, three defining characteristics are given:')
print('  startTime : at what time does the job enter the system')
print('  runTime   : the total CPU time needed by the job to finish')
print('  ioFreq    : every ioFreq time units, the job issues an I/O')
print('              (the I/O takes ioTime units to complete)\n')

print('Job List:')
for i in range(numJobs):
    print('  Job %2d: startTime %3d - runTime %3d - ioFreq %3d' % (i, job[i]['startTime'],
                                                                   job[i]['runTime'],
                                                                   job[i]['ioFreq']))
print('')

if options.solve == False:
    print('Compute the execution trace for the given workloads.')
    print('If you would like, also compute the response and turnaround')
    print('times for each of the jobs.')
    print('')
    print('Use the -c flag to get the exact results when you are finished.\n')
    exit(0)

# initialize the MLFQ queues
queue = {}
for q in range(numQueues):
    queue[q] = []

# TIME IS CENTRAL
currTime = 0

# use these to know when we're finished
totalJobs    = len(job)
finishedJobs = 0

print('\nExecution Trace:\n')

while finishedJobs < totalJobs:
    # find highest priority job
    # run it until either
    # (a) the job uses up its time quantum
    # (b) the job performs an I/O

    # check for priority boost
    if options.boost > 0 and currTime != 0:
        if currTime % options.boost == 0:
            print('[ time %d ] BOOST ( every %d )' % (currTime, options.boost))
            # remove all jobs from queues (except high queue) and put them in high queue
            for q in range(numQueues-1):
                for j in queue[q]:
                    if job[j]['doingIO'] == False:
                        queue[hiQueue].append(j)
                queue[q] = []

            # change priority to high priority
            # reset number of ticks left for all jobs (just for lower jobs?)
            # add to highest run queue (if not doing I/O)
            for j in range(numJobs):
                # print '-> Boost %d (timeLeft %d)' % (j, job[j]['timeLeft'])
                if job[j]['timeLeft'] > 0:
                    # print '-> FinalBoost %d (timeLeft %d)' % (j, job[j]['timeLeft'])
                    job[j]['currPri']   = hiQueue
                    job[j]['ticksLeft'] = allotment[hiQueue]
            # print 'BOOST END: QUEUES look like:', queue

    # check for any I/Os done
    if currTime in ioDone:
        for (j, type) in ioDone[currTime]:
            q = job[j]['currPri']
            job[j]['doingIO'] = False
            print('[ time %d ] %s by JOB %d' % (currTime, type, j))
            if options.iobump == False or type == 'JOB BEGINS':
                queue[q].append(j)
            else:
                queue[q].insert(0, j)

    # now find the highest priority job
    currQueue = FindQueue()
    if currQueue == -1:
        print('[ time %d ] IDLE' % (currTime))
        currTime += 1
        continue

    # there was at least one runnable job, and hence ...
    currJob = queue[currQueue][0]
    if job[currJob]['currPri'] != currQueue:
        Abort('currPri[%d] does not match currQueue[%d]' % (job[currJob]['currPri'], currQueue))

    job[currJob]['timeLeft']  -= 1
    job[currJob]['ticksLeft'] -= 1

    if job[currJob]['firstRun'] == -1:
        job[currJob]['firstRun'] = currTime

    runTime   = job[currJob]['runTime']
    ioFreq    = job[currJob]['ioFreq']
    ticksLeft = job[currJob]['ticksLeft']
    allotLeft = job[currJob]['allotLeft']
    timeLeft  = job[currJob]['timeLeft']

    print('[ time %d ] Run JOB %d at PRIORITY %d [ TICKS %d ALLOT %d TIME %d (of %d) ]' % \
          (currTime, currJob, currQueue, ticksLeft, allotLeft, timeLeft, runTime))

    if timeLeft < 0:
        Abort('Error: should never have less than 0 time left to run')


    # UPDATE TIME
    currTime += 1

    # CHECK FOR JOB ENDING
    if timeLeft == 0:
        print('[ time %d ] FINISHED JOB %d' % (currTime, currJob))
        finishedJobs += 1
        job[currJob]['endTime'] = currTime
        # print 'BEFORE POP', queue
        done = queue[currQueue].pop(0)
        # print 'AFTER POP', queue
        assert(done == currJob)
        continue

    # CHECK FOR IO
    issuedIO = False
    if ioFreq > 0 and (((runTime - timeLeft) % ioFreq) == 0):
        # time for an IO!
        print('[ time %d ] IO_START by JOB %d' % (currTime, currJob))
        issuedIO = True
        desched = queue[currQueue].pop(0)
        assert(desched == currJob)
        job[currJob]['doingIO'] = True
        # this does the bad rule -- reset your tick counter if you stay at the same level
        if options.stay == True:
            job[currJob]['ticksLeft'] = quantum[currQueue]
            job[currJob]['allotLeft'] = allotment[currQueue]
        # add to IO Queue: but which queue?
        futureTime = currTime + ioTime
        if futureTime not in ioDone:
            ioDone[futureTime] = []
        print('IO DONE')
        ioDone[futureTime].append((currJob, 'IO_DONE'))

    # CHECK FOR QUANTUM ENDING AT THIS LEVEL (BUT REMEMBER, THERE STILL MAY BE ALLOTMENT LEFT)
    if ticksLeft == 0:
        if issuedIO == False:
            # IO HAS NOT BEEN ISSUED (therefor pop from queue)'
            desched = queue[currQueue].pop(0)
        assert(desched == currJob)

        job[currJob]['allotLeft'] = job[currJob]['allotLeft'] - 1

        if job[currJob]['allotLeft'] == 0:
            # this job is DONE at this level, so move on
            if currQueue > 0:
                # in this case, have to change the priority of the job
                job[currJob]['currPri']   = currQueue - 1
                job[currJob]['ticksLeft'] = quantum[currQueue-1]
                job[currJob]['allotLeft'] = allotment[currQueue-1]
                if issuedIO == False:
                    queue[currQueue-1].append(currJob)
            else:
                job[currJob]['ticksLeft'] = quantum[currQueue]
                job[currJob]['allotLeft'] = allotment[currQueue]
                if issuedIO == False:
                    queue[currQueue].append(currJob)
        else:
            # this job has more time at this level, so just push it to end
            job[currJob]['ticksLeft'] = quantum[currQueue]
            if issuedIO == False:
                queue[currQueue].append(currJob)




# print out statistics
print('')
print('Final statistics:')
responseSum   = 0
turnaroundSum = 0
for i in range(numJobs):
    response   = job[i]['firstRun'] - job[i]['startTime']
    turnaround = job[i]['endTime'] - job[i]['startTime']
    print('  Job %2d: startTime %3d - response %3d - turnaround %3d' % (i, job[i]['startTime'],
                                                                        response, turnaround))
    responseSum   += response
    turnaroundSum += turnaround

print('\n  Avg %2d: startTime n/a - response %.2f - turnaround %.2f' % (i,
                                                                        float(responseSum)/numJobs,
                                                                        float(turnaroundSum)/numJobs))

print('\n')

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/495195.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【快捷部署】010_MySQL(5.7.27)

&#x1f4e3;【快捷部署系列】010期信息 编号选型版本操作系统部署形式部署模式复检时间010MySQL5.7.27Ubuntu 20.04Docker单机2024-03-28 一、快捷部署 #!/bin/bash ################################################################################# # 作者&#xff1a…

idea类已经存在却报错

一句话导读 在idea中导入新的项目&#xff0c;很多类都飘红报错&#xff0c;mvn compile可以通过&#xff0c;可能是因为idea缓存问题导致。 由于这个项目是由老项目复制过来后&#xff0c;再继续开发新的功能&#xff0c;很多同事导入后&#xff0c;都爆出新的类找不到。而编译…

正弦实时数据库(SinRTDB)的使用(4)-快照查询

前文已经将松果实时数据库的安装、创建点表、创建测点、接入OPC DA的数据进行了介绍&#xff0c;没有了解的可以先看如下博客&#xff1a; 正弦实时数据库(SinRTDB)的安装 正弦实时数据库(SinRTDB)的使用(1)-使用数据发生器写入数据 正弦实时数据库(SinRTDB)的使用(2)-接入O…

【吊打面试官系列】Redis篇 -怎么测试 Redis 的连通性?

大家好&#xff0c;我是锋哥。今天分享关于 【怎么测试 Redis 的连通性&#xff1f;】面试题&#xff0c;希望对大家有帮助&#xff1b; 怎么测试 Redis 的连通性&#xff1f; 使用 ping 命令。 要测试Redis的连通性&#xff0c;可以使用redis-cli命令行工具或编写代码。以下是…

Docker 哲学 - Dockerfile 指令

Dockerfile 的 entrypoint 和 cmd 书写方式一样吗&#xff0c;分别用一个node项目的 demo来举例 Dockerfile 的 entrypoint 、cmd 有什么区别&#xff0c;分别举例他们同时出现的场景和 单独出现的场景 entrypoint 和 cmd 命令&#xff1a; 同时出现&#xff1a; 1、cmd 作为 e…

格式化危机!教你轻松恢复数据!

一、遭遇格式化&#xff0c;数据恢复并非难事 当存储设备遭遇格式化后&#xff0c;许多人可能会陷入恐慌&#xff0c;担心重要数据一去不复返。但实际上&#xff0c;数据恢复并非如想象中那般困难。格式化操作主要清除了文件系统的索引信息&#xff0c;而实际的数据往往还残留…

[STM32] Keil 创建 HAL 库的工程模板

Keil 创建 HAL 库的工程模板 跟着100ASK_STM32F103_MINI用户手册V1.1.pdf的第7章步骤进行Keil工程的创建。 文章目录 1 创建相关文件夹2 创建“main.c/h”和“stm32f1xx_clk.c/h”3 复制CMSIS和HAL库4 创建新的Keil工程5 添加组文件夹和工程文件6 配置Keil设置 1 创建相关文件…

Ollama使用

当前各种大模型层出不穷&#xff0c;但想要在本地运行起来一个大模型还是有一定门槛的。 并且模型众多&#xff0c; 每个模型都有自己不同的配置和使用方法&#xff0c;使用非常不便。 Ollama就是一个非常好的工具&#xff0c; 可以让你方便在本地运行各种大模型。 1 安装 支…

【前端学习——js篇】11.元素可见区域

具体见&#xff1a;https://github.com/febobo/web-interview 11.元素可见区域 ①offsetTop、scrollTop offsetTop&#xff0c;元素的上外边框至包含元素的上内边框之间的像素距离&#xff0c;其他offset属性如下图所示&#xff1a; 下面再来了解下clientWidth、clientHeight…

报错there is no HDFS_NAMENODE_USER defined

在Hadoop安装目录下找到sbin文件夹&#xff0c;修改里面的四个文件 1、对于start-dfs.sh和stop-dfs.sh文件&#xff0c;添加下列参数&#xff1a; HDFS_DATANODE_USERroot HDFS_DATANODE_SECURE_USERhdfs HDFS_NAMENODE_USERroot HDFS_SECONDARYNAMENODE_USERroot 2、对于st…

云贝教育 |【技术文章】pg_bulkload介绍

注: 本文为云贝教育 刘峰 原创&#xff0c;请尊重知识产权&#xff0c;转发请注明出处&#xff0c;不接受任何抄袭、演绎和未经注明出处的转载。 pg_bulkload 是一个高性能的数据加载工具&#xff0c;专门为PostgreSQL数据库设计&#xff0c;用于大批量数据的快速导入。pg_bulk…

【YOLOV5 入门】——detect.py简单解析模型检测基于torch.hub的检测方法

声明&#xff1a;笔记是毕设时根据B站博主视频学习时自己编写&#xff0c;请勿随意转载&#xff01; 一、打开detect.py&#xff08;文件解析&#xff09; 打开上节桌面创建的yolov5-7.0文件夹里的detect.py文件&#xff08;up主使用的是VScode&#xff0c;我这里使用pycharm…

电商数据采集平台兼具海量采集国内淘系京东国外LAZADA亚马逊阿里巴巴等平台数据采集

很多的电商数据采集API接口可以使用国内电商平台淘系、京东的行业数据&#xff0c;境外Lazada等平台的行业数据&#xff0c;以及各类直播电商数据等&#xff0c;相对淘数据来说&#xff0c;平台更多一些&#xff0c;但是价格也比较贵&#xff0c;一般是按照行业下类目来销售的&…

华为耳机快速配对新设备,一招搞定

耳机现在已经是我们形影不离的随身设备&#xff0c;如果我们碰见华为手机或平板无法连接或连接不上华为耳机&#xff08;如FreeBuds、FreeLace系列及FreeClip蓝牙耳机&#xff09;的问题&#xff0c;其实很简单&#xff0c;今天分享一个小妙招&#xff0c;帮助我们快速解决这个…

ConcurrentHashMap 是如何保证并发安全的

ConcurrentHashMap JDK1.7 ConcurrentHashMap 是如何保证并发安全的&#xff1f;使用分段锁的概念&#xff1a; 例如这张图&#xff0c;共有 256 个槽位&#xff0c;如果整个哈希表用一把锁&#xff0c;势必性能低下 如果256个槽位&#xff0c;每个槽位都有一把锁&#xff0…

懒人方法|(一)分享:NHANES数据库怎么下载整理

1.前言 继前面孟德尔随机化的代码分享&#xff0c;应粉丝要求出一篇关于NHANES数据库的数据整理入门教程 前面MR代码&#xff1a;全代码分享&#xff5c;R语言孟德尔随机化怎么做&#xff1f;TwoSampleMR包MR一套标准流程 2.数据库界面 NHANES&#xff08;National Health …

数据结构算法刷题笔记——题型解法

数据结构算法刷题笔记——题型解法 一、常用容器1.1 vector1.1.1 vector基本操作1.1.1.0 头文件#include<vector>1.1.1.1 构造一个vector容器1.1.1.2 元素访问1.1.1.3 元素个数 .size()1.1.1.4 最大容量 .capacity()1.1.1.5 改变容器有效元素个数 .resize(n)1.1.1.6 改变…

详解智慧路灯杆网关的集中供电能力

智慧路灯杆网关是智慧杆物联网系统中不可或缺的设备。智慧杆网关不仅可以作为杆载设备与云平台、设备与设备之间的桥梁&#xff0c;促进数据的无缝传输&#xff0c;而且还能提供高效的能源管理和供电功能。 BMG8200系列交流型智慧路灯杆网关就集成了强大的供电能力&#xff0c;…

数字信号转模拟信号 DA变换 高精度PWM脉宽调制信号100Hz PWM/5KHz PWM /10KHz PWM转4-20mA/0-10V/1-5V/0-5V

主要特性: >>精度等级&#xff1a;0.1级。产品出厂前已检验校正&#xff0c;用户可以直接使用 >>辅助电源&#xff1a;8-32V 宽范围供电 >>PWM脉宽调制信号输入: 1Hz~10KHz >>输出标准信号&#xff1a;0-5V/0-10V/1-5V,0-10mA/0-20mA/4-20mA等&…

如何确保六西格玛培训效果最大化?

近年来&#xff0c;如何确保六西格玛培训的效果&#xff0c;使其真正转化为企业的生产力&#xff0c;成为许多管理者关注的焦点。本文&#xff0c;天行健Six Sigma咨询公司将分享如何确保六西格玛培训效果最大化&#xff0c;帮助企业在实施六西格玛管理的过程中取得更好的成效。…