Skoči na vsebino

P1 - Dodatna naloga

from random import Random
from time import time
from multiprocessing import cpu_count, Process, Manager

processCount = int(input("Amount of processes (%s): " % cpu_count()) or cpu_count())
calcRange = range(0, int(input("Use seeds from 0 to (9999): ") or 9999) + 1)

# start credits: https://stackoverflow.com/a/2130035/11276254
calcRanges = []
calcRangesAvg = len(calcRange) / float(processCount)
calcRangesLast = 0.0

while calcRangesLast < len(calcRange):
    calcRanges.append(calcRange[int(calcRangesLast):int(calcRangesLast + calcRangesAvg)])
    calcRangesLast += calcRangesAvg
# end credits


def tryRange (tIndex, range, data):
    print("Process started: %2s; range: %s" % (tIndex, range))
    timestart = time()
    threadRandom = Random()
    minThrows = 999999999
    minSeed = 0
    
    for sIndex in range:
        threadRandom.seed(sIndex)

        countThrow = 0
        countFive = 0
        pos = 0

        while (countFive < 100):
            throwVal = threadRandom.randint(1, 6)
            pos = (pos + throwVal) % 6
            if (pos == 5):
                countFive += 1

            countThrow += 1
            
        if (countThrow < minThrows):
            minThrows = countThrow
            minSeed = sIndex
    
    timeend = time()
    data.append((minSeed, minThrows, ))
    print("Process ended: %2s; min throws: %4s; with seed: %6s; runtime: %6s sec" % (tIndex, minThrows, minSeed, timeend - timestart))



if __name__ == "__main__":
    mainStart = time()
    with Manager() as manager:
        data = manager.list()

        threads = [None] * processCount

        for tIndex in range(processCount):
            threads[tIndex] = Process(target=tryRange, args=(tIndex, calcRanges[tIndex], data, ))
            print("Process created: %2s" % tIndex)
            
        print("\n")

        for t in threads:
            t.start()        
        for t in threads:
            t.join()

        print("\n")

        mainEnd = time()

        min = (0, 9999999)
        for i in data:
            if (i[1] < min[1]):
                min = i

        print("\n\nGenerated the min. value of %s with seed %s in %s sec" % ( min[1], min[0], mainEnd - mainStart ))

Zadnja posodobitev: February 27, 2022