Alle Dateien aus dem Pythonkurs
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.

53 lines
1.8 KiB

2 years ago
# encoding: UTF-8
from timeit import default_timer as timer
import datetime
import multiprocessing
import time
import random
from multiprocessing import Pool
def func1(*args, **kwargs):
sleep_time = random.randint(3, 6)
print(f'Prozess : {multiprocessing.current_process().name}\tFunktion : func1\tArgs:{args}\tgeschlafen {sleep_time} \tZeit : {datetime.datetime.now()}\n')
print("Keyword Args from func1: %s" % kwargs)
time.sleep(sleep_time)
print(f'{multiprocessing.current_process().name}\t func1 fertig: {datetime.datetime.now()}\n')
return sum(*args)
def func2(*args):
sleep_time = random.randint(7, 10)
print(f'Prozess : {multiprocessing.current_process().name}\tFunktion : func2\tArgs:{args}\tgeschlafen {sleep_time} \tZeit : {datetime.datetime.now()}\n')
time.sleep(sleep_time)
print(f'{multiprocessing.current_process().name}\t func2 fertig: {datetime.datetime.now()}\n')
return sum(*args)
def func3(*args):
sleep_time = random.randint(0, 3)
print(f'Prozess : {multiprocessing.current_process().name}\tFunktion : func3\ttArgs:{args}\tgeschlafen {sleep_time} \tZeit : {datetime.datetime.now()}\n')
time.sleep(sleep_time)
print(f'{multiprocessing.current_process().name}\t func3 fertig: {datetime.datetime.now()}\n')
return sum(*args)
def smap(f, *arg):
if len(arg) == 2:
args, kwargs = arg
return f(list(args), **kwargs)
elif len(arg) == 1:
args = arg
return f(*args)
if __name__ == '__main__':
start = timer()
with Pool(processes=3) as pool:
result = pool.starmap(smap, [(func1, [1,2,3],{'a':123, 'b':456}), (func2, [11,22,33]), (func3, [111,222,333])])
print(f'Ergebnis: {result}')
ende = timer()
diff = ende - start
print(f'Ausführzeit: {diff}s')