Efectes del GIL de python¶
El fitxer calculs.py cronometra l’engegada i finalització de un nombre de processos (que poden ser o dorm o bé calcula) mitjançant fils del mòdul threading o bé processos del mòdul processing.
Baixeu-vos calculs.py i feu proves
import os
import sys
import time
import threading
import multiprocessing
def identif():
print("PID: %s, Nom procés: %s, Nom fil: %s" % (
os.getpid(),
multiprocessing.current_process().name,
threading.current_thread().name)
)
def dorm():
identif()
time.sleep(1)
def calcula():
identif()
x = 0
while x < 10000000:
x += 1
def provaConcurrencia(nProc, funcio):
tempsIni = time.time()
for _ in range(nProc):
funcio()
tempsFi = time.time()
print("Temps seqüencial=", tempsFi - tempsIni)
tempsIni = time.time()
fils = [threading.Thread(target=funcio) for _ in range(nProc)]
for fil in fils:
fil.start()
for fil in fils:
fil.join()
tempsFi = time.time()
print("Temps fils=", tempsFi - tempsIni)
tempsIni = time.time()
processos = [multiprocessing.Process(target=funcio) for _ in range(nProc)]
for proces in processos:
proces.start()
for proces in processos:
proces.join()
tempsFi = time.time()
print("Temps paral·lel=", tempsFi - tempsIni)
if __name__ == '__main__':
if len(sys.argv) == 1:
provaConcurrencia(5, calcula)
elif len(sys.argv) == 2:
provaConcurrencia(int(sys.argv[1]), calcula)
elif len(sys.argv) == 3:
if sys.argv[2] == 'calcula':
f = calcula
elif sys.argv[2] == 'dorm':
f = dorm
else:
print('Ús: ',sys.argv[0], ' [nombreProcessos] [calcula|dorm]')
raise Exception('procés no identificat')
provaConcurrencia(int(sys.argv[1]), f)