venerdì 10 maggio 2013

astenersi perditempo seriali


esempio banale che illustra come poter dormire per più di un secondo al secondo.

#! /usr/bin/env python

import multiprocessing
from time import time, sleep
import random
import sys, os

# how big is the process pool

POOLSIZE = 5

# how many (named) works to process
BEDS = ["b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9"]
sleepList = BEDS[0:POOLSIZE] * 10

    
def PerdiTempo(aSleepName):
    currtime = time()
    name = multiprocessing.current_process().name
    rc = random.randint(1,10)
    sleep(rc)
    sys.stderr.write("name %s, pid: %d - (bed %s) - sleep %d. time elapsed %f\n" % (name, os.getpid(), aSleepName, rc, time() - currtime))
    return rc

if __name__ == "__main__":
    currtime = time()
    print "%s started, pid: %d, pool size: %d" % (sys.argv[0], os.getpid(), POOLSIZE)
    print "to sleep:", sleepList
    po = multiprocessing.Pool(POOLSIZE)
    res = po.map_async(PerdiTempo,(i for i in sleepList))
    w = sum(res.get())
    print "total time lost: %d (sec.)" % (w,)
    elap = time() - currtime
    print 'pid: %d ended, pool size of %d workers. time elapsed: %f (sec.). speedup: %5.2fx' % (os.getpid(), POOLSIZE, elap, w/elap)

Nessun commento:

Posta un commento