Skip to content

Instantly share code, notes, and snippets.

@jhemarcos
Last active July 5, 2017 15:07
Show Gist options
  • Save jhemarcos/61585abd4a3051b934b2c0a4db2b1372 to your computer and use it in GitHub Desktop.
Save jhemarcos/61585abd4a3051b934b2c0a4db2b1372 to your computer and use it in GitHub Desktop.
Código de teste em python para verificar a diferenciação em tempos de execução de cargas CPU Bound utilizando modelos seriais, com threads e futures, mostrando a influência da GIL no desempenho.
import timeit
import threading
from concurrent.futures import ProcessPoolExecutor
#10 milhoes
loop = 10000000;
#Realiza 10 milhoes de concatenacoes
def worker():
for x in range(0, loop):
y = "Loop " + str(x)
#Executa dois worker com thread
def threadGroup():
t1 = threading.Thread(target=worker)
t2 = threading.Thread(target=worker)
t1.start()
t2.start()
while t1.isAlive() & t2.isAlive():
pass
#Executa dois workers serial
def serialGroup():
worker()
worker()
#Executa dois workers de forma paralela com futures
def futureGroup():
pool = ProcessPoolExecutor(2)
f1 = pool.submit(worker)
f2 = pool.submit(worker)
while (not f1.done()) & (not f2.done()):
pass
print "Tempos para " + str(loop * 2) + " de concatenacoes:"
#Calculando tempo com threads
timer1 = timeit.Timer("threadGroup()", "from __main__ import threadGroup")
print "Com threads (GIL): " + str(round(timer1.repeat(1, 1)[0], 5)) + " segundos."
#Calculando tempo serial
timer2 = timeit.Timer("serialGroup()", "from __main__ import serialGroup")
print "Serial: " + str(round(timer2.repeat(1, 1)[0], 5))+ " segundos."
#Calculando tempo com future
timer3 = timeit.Timer("futureGroup()", "from __main__ import futureGroup")
print "Com futures: " + str(round(timer3.repeat(1, 1)[0], 5))+ " segundos."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment