SlideShare a Scribd company logo
Alta Performance com
Python
Paralelismo e Concorrência
Alta Performance com Python
Paralelismo e Concorrência
BrunoBarbosa
Desenvolvedor de Software na Globo.com
Há 7 anos escrevendo software profissionalmente
Programador por diversão há 14 anos
Apaixonado por Python e todo seu ecossistema
Trabalhando atualmente na maior parte do tempo com
Python, Go e JavaScript.
Iniciou sua carreira trabalhando com Python, Zope e
Plone
Brasiliense se aventurando pelo errejota :)
Mais de
50milhões
de visitas por dia
Homesda
Globo.com
Processos
Threadse
ThreadsProcessos
Compartilham memória
Custo de spawn/switch
Necessidade de recursos
Mecanismos de
sincronização
Processos Threadse
Comparativo
PROCESSO1
DADOS
COMPARTILHADOS
PELASTHREADS
THREAD1 THREAD2 THREAD3
DADOS DADOS DADOS
Processos Threadse
Anatomia de um processo
PROCESSO1 PROCESSO2
DADOS
COMPARTILHADOS
PELASTHREADS
THREAD THREAD THREAD
DADOS DADOS DADOS
DADOS
COMPARTILHADOS
PELASTHREADS
THREAD THREAD THREAD
DADOS DADOS DADOS
Processos Threadse
Anatomia de um processo
CPUBOUND
I/OBOUND
e
Processos Threadse
Tipos de processos
CPUBOUND I/OBOUND
Processos Threadse
Tipos de processos
Computações matemáticas
intensas
Algoritmos de busca e ordenação
em memória
Processamento e
reconhecimento de imagem
Transferência de dados pela rede
Escrita de arquivo em disco
Consulta a uma API HTTP
ConcorrênciaParalelismo
Como funciona
Concorrência Paralelismoe
PRO
CES
SO
THREAD1
CPU
THREAD2
THREAD3
CONCORRÊNCIA
PROCESSING IDLE
Como funciona
Concorrência Paralelismoe
PRO
CES
SO
THREAD1
CPU
THREAD2
THREAD3
PARALELISMO
PRO
CES
SO
THREAD1
CPU
THREAD2
THREAD3
VAMOS FALAR DE
PYTHON
O famigerado GIL
(Global Interpreter Lock)
import multiprocessing
import os
import threading
import time
MAX_WORKERS = 4



def io_expensive(sleep_time=1):
""" Do nothing, wait for a timer to expire """
print("PID: {}, Process Name: {}, Thread Name: {}".format(
os.getpid(),
multiprocessing.current_process().name,
threading.current_thread().name)
)
time.sleep(sleep_time)
Simulando uma atividade de rede
I/O Bound
Simulando uma atividade de rede
I/O Bound
1ºTeste:Sequencial
import time
from main_example import MAX_WORKERS, io_expensive



start_time = time.time()
for i in range(MAX_WORKERS):
io_expensive(i)
end_time = time.time()
print("n✔ Serial time=", end_time - start_time)
Simulando uma atividade de rede
I/O Bound
2ºTeste:Threads
import time
from concurrent import futures
from main_example import MAX_WORKERS, io_expensive
start_time = time.time()
with futures.ThreadPoolExecutor(MAX_WORKERS) as executor:
executor.map(io_expensive, range(MAX_WORKERS))
end_time = time.time()
print("n✔ Threads time=", end_time - start_time)
Simulando uma atividade de rede
I/O Bound
2ºTeste:Threads
import time
from concurrent import futures
from main_example import MAX_WORKERS, io_expensive
start_time = time.time()
with futures.ThreadPoolExecutor(MAX_WORKERS) as executor:
executor.map(io_expensive, range(MAX_WORKERS))
end_time = time.time()
print("n✔ Threads time=", end_time - start_time)
Simulando uma atividade de rede
I/O Bound
3ºTeste:Processos
import time
from concurrent import futures
from main_example import MAX_WORKERS, io_expensive
start_time = time.time()
with futures.ProcessPoolExecutor() as executor:
executor.map(io_expensive, range(MAX_WORKERS))
end_time = time.time()
print("n✔ Parallel time=", end_time - start_time)
Simulando uma atividade de rede
I/O Bound
3ºTeste:Processos
import time
from concurrent import futures
from main_example import MAX_WORKERS, io_expensive
start_time = time.time()
with futures.ProcessPoolExecutor() as executor:
executor.map(io_expensive, range(MAX_WORKERS))
end_time = time.time()
print("n✔ Parallel time=", end_time - start_time)
Simulando uma atividade de rede
I/O Bound
import multiprocessing
import os
import threading
import time
MAX_WORKERS = 4



def cpu_expensive():
""" Do some computations """
print("PID: {}, Process Name: {}, Thread Name: {}".format(
os.getpid(),
multiprocessing.current_process().name,
threading.current_thread().name)
)
x = 0
while x < 10000000:
x += 1
Simulando uma atividade de alto processamento
CPU Bound
1ºTeste:Sequencial
import time
from main_example import MAX_WORKERS, cpu_expensive



start_time = time.time()
for i in range(MAX_WORKERS):
cpu_expensive()
end_time = time.time()
print("n✔ Serial time=", end_time - start_time)
Simulando uma atividade de alto processamento
CPU Bound
2ºTeste:Threads
import time
from concurrent import futures
from main_example import MAX_WORKERS, cpu_expensive
start_time = time.time()
with futures.ThreadPoolExecutor(MAX_WORKERS) as executor:
for _ in range(MAX_WORKERS):
executor.submit(cpu_expensive)
end_time = time.time()
print("n✔ Threads time=", end_time - start_time)
Simulando uma atividade de alto processamento
CPU Bound
Simulando uma atividade de rede
I/O Bound
2ºTeste:Threads

import time
from concurrent import futures
from main_example import MAX_WORKERS, cpu_expensive
start_time = time.time()
with futures.ThreadPoolExecutor(MAX_WORKERS) as executor:
for _ in range(MAX_WORKERS):
executor.submit(cpu_expensive)
end_time = time.time()
print("n✔ Threads time=", end_time - start_time)
3ºTeste:Processos
import time
from concurrent import futures
from main_example import MAX_WORKERS, io_expensive
start_time = time.time()
with futures.ProcessPoolExecutor() as executor:
for _ in range(MAX_WORKERS):
executor.submit(cpu_expensive)
end_time = time.time()
print("n✔ Parallel time=", end_time - start_time)
Simulando uma atividade de alto processamento
CPU Bound
Simulando uma atividade de rede
I/O Bound
3ºTeste:Processos
import time
from concurrent import futures
from main_example import MAX_WORKERS, io_expensive
start_time = time.time()
with futures.ProcessPoolExecutor() as executor:
for _ in range(MAX_WORKERS):
executor.submit(cpu_expensive)
end_time = time.time()
print("n✔ Parallel time=", end_time - start_time)
Simulando uma atividade de alto processamento
CPU Bound
OS MÓDULOS
THREADING e
MULTIPROCESSING
PARA CASOS MAIS COMPLEXOS USE
E O TAL DO
ASYNC/AWAIT?
GERADORES!!!
Produzindo valores através de yield
Generators
def gen_integer():
print("Calling for fist time""...")
yield 1
print("Calling for second time""...")
yield 2
print("Calling for third time""...")
yield 3
"">>> next(gen)
Calling for fist time…
1
"">>> next(gen)
Calling for second time…
2
"">>> gen = gen_integer()
"">>> next(gen)
Calling for third time…
3
Traceback (most recent
call last):
""...
StopIteration
"">>> next(gen)
Produzindo valores através de yield
Generators
def gen_fruit():
fruits = ['apple', 'banana', 'grape']
for fruit in fruits:
yield fruit
"">>> basket = gen_fruit()
"">>> for fruit in basket:
print(f"Got: {fruit}")
Got: apple
Got: banana
Got: grape
Usando yield from
Generators
def gen_fruit():
fruits = ['apple', 'banana', 'grape']
for fruit in fruits:
yield fruit
"">>> basket = gen_fruit()
"">>> for fruit in basket:
print(f"Got: {fruit}")
Got: apple
Got: banana
Got: grape
def gen_fruit():
fruits = ['apple', 'banana', 'grappes']
yield from fruits
Coroutines
Coroutines
Um gerador melhorado
def example_coro():
print("""--> Execution started")
x = yield
print(f"""--> Received value: {x}")
def main():
coro = example_coro()
print("""==> Preparing the coroutine""...")
next(coro)
print("""==> sending a value to coroutine: ")
coro.send(42)
""==> Preparing the coroutine…
""--> Execution started
""==> sending a value to coroutine:
""--> Received value: 42
Traceback (most recent call last):
""...
StopIteration
Coroutines
Um gerador melhorado
Coroutines
Um gerador melhorado
def example_coro_2(start_num):
print("""--> Example started!")
value = yield start_num
print(f"""--> Received: {value}")
yield start_num + value
def example_2():
coro = example_coro_2(20)
initial_value = next(coro)
print(f"""==> Initial value: {initial_value}")
v = coro.send(22)
print(f"""==> sum: {v}")
next(coro)
""--> Example started!
""==> Initial value: 20
""--> Received: 22
""==> sum: 42
Traceback (most recent call last):
""...
StopIteration
Coroutines
Um gerador melhorado
ASYNC/AWAIT
ASYNC / AWAIT
Código assíncrono através de corrotinas
import asyncio
import time
@asyncio.coroutine
def say_after(delay, what):
yield from asyncio.sleep(delay)
print(what)
@asyncio.coroutine
def main():
print('started at', time.strftime('%X'))
yield from say_after(1, 'hello')
yield from say_after(2, 'world')
print('finished at', time.strftime('%X'))
asyncio.run(main())
ASYNC / AWAIT
Código assíncrono através de corrotinas
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print('started at', time.strftime('%X'))
await say_after(1, 'hello')
await say_after(2, 'world')
print('finished at', time.strftime('%X'))
asyncio.run(main())
ASYNC / AWAIT
Fazendo requisições HTTP com o método aiohttp
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http:"//python.org')
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
We’reHiring!!!
TEMOSVAGAS!!!
TALENTOS.GLOBO.COM
@brunobbbs
Contato
Onde me encontrar

More Related Content

What's hot

Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
Oliver N
 
Do snow.rwn
Do snow.rwnDo snow.rwn
Do snow.rwn
ARUN DN
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
Geeks Anonymes
 
Infrastructure as Data - PuppetConf 2013
Infrastructure as Data - PuppetConf 2013Infrastructure as Data - PuppetConf 2013
Infrastructure as Data - PuppetConf 2013
Puppet
 
Kotlin - Coroutine
Kotlin - CoroutineKotlin - Coroutine
Kotlin - Coroutine
Sean Tsai
 
Slides Δικτυακών Υπολογισμών με την Python
Slides Δικτυακών Υπολογισμών με την PythonSlides Δικτυακών Υπολογισμών με την Python
Slides Δικτυακών Υπολογισμών με την Python
Moses Boudourides
 
Implementing Software Machines in Go and C
Implementing Software Machines in Go and CImplementing Software Machines in Go and C
Implementing Software Machines in Go and C
Eleanor McHugh
 
Go Containers
Go ContainersGo Containers
Go Containers
jgrahamc
 
Python and sysadmin I
Python and sysadmin IPython and sysadmin I
Python and sysadmin I
Guixing Bai
 
Txjs
TxjsTxjs
Diving into byte code optimization in python
Diving into byte code optimization in python Diving into byte code optimization in python
Diving into byte code optimization in python
Chetan Giridhar
 
RabbitMQ
RabbitMQRabbitMQ
RabbitMQ
voluntas
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
Eleanor McHugh
 
Go serving: Building server app with go
Go serving: Building server app with goGo serving: Building server app with go
Go serving: Building server app with go
Hean Hong Leong
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
akaptur
 
KubeCon EU 2016: Custom Volume Plugins
KubeCon EU 2016: Custom Volume PluginsKubeCon EU 2016: Custom Volume Plugins
KubeCon EU 2016: Custom Volume Plugins
KubeAcademy
 
Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs -  NCrafts Paris 2015Build a compiler in 2hrs -  NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015
Phillip Trelford
 
Go for the paranoid network programmer, 3rd edition
Go for the paranoid network programmer, 3rd editionGo for the paranoid network programmer, 3rd edition
Go for the paranoid network programmer, 3rd edition
Eleanor McHugh
 
Ανάλυση Δικτύων με το NetworkX της Python: Μια προκαταρκτική (αλλά ημιτελής ω...
Ανάλυση Δικτύων με το NetworkX της Python: Μια προκαταρκτική (αλλά ημιτελής ω...Ανάλυση Δικτύων με το NetworkX της Python: Μια προκαταρκτική (αλλά ημιτελής ω...
Ανάλυση Δικτύων με το NetworkX της Python: Μια προκαταρκτική (αλλά ημιτελής ω...
Moses Boudourides
 
Go a crash course
Go   a crash courseGo   a crash course
Go a crash course
Eleanor McHugh
 

What's hot (20)

Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
 
Do snow.rwn
Do snow.rwnDo snow.rwn
Do snow.rwn
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Infrastructure as Data - PuppetConf 2013
Infrastructure as Data - PuppetConf 2013Infrastructure as Data - PuppetConf 2013
Infrastructure as Data - PuppetConf 2013
 
Kotlin - Coroutine
Kotlin - CoroutineKotlin - Coroutine
Kotlin - Coroutine
 
Slides Δικτυακών Υπολογισμών με την Python
Slides Δικτυακών Υπολογισμών με την PythonSlides Δικτυακών Υπολογισμών με την Python
Slides Δικτυακών Υπολογισμών με την Python
 
Implementing Software Machines in Go and C
Implementing Software Machines in Go and CImplementing Software Machines in Go and C
Implementing Software Machines in Go and C
 
Go Containers
Go ContainersGo Containers
Go Containers
 
Python and sysadmin I
Python and sysadmin IPython and sysadmin I
Python and sysadmin I
 
Txjs
TxjsTxjs
Txjs
 
Diving into byte code optimization in python
Diving into byte code optimization in python Diving into byte code optimization in python
Diving into byte code optimization in python
 
RabbitMQ
RabbitMQRabbitMQ
RabbitMQ
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
 
Go serving: Building server app with go
Go serving: Building server app with goGo serving: Building server app with go
Go serving: Building server app with go
 
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
 
KubeCon EU 2016: Custom Volume Plugins
KubeCon EU 2016: Custom Volume PluginsKubeCon EU 2016: Custom Volume Plugins
KubeCon EU 2016: Custom Volume Plugins
 
Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs -  NCrafts Paris 2015Build a compiler in 2hrs -  NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015
 
Go for the paranoid network programmer, 3rd edition
Go for the paranoid network programmer, 3rd editionGo for the paranoid network programmer, 3rd edition
Go for the paranoid network programmer, 3rd edition
 
Ανάλυση Δικτύων με το NetworkX της Python: Μια προκαταρκτική (αλλά ημιτελής ω...
Ανάλυση Δικτύων με το NetworkX της Python: Μια προκαταρκτική (αλλά ημιτελής ω...Ανάλυση Δικτύων με το NetworkX της Python: Μια προκαταρκτική (αλλά ημιτελής ω...
Ανάλυση Δικτύων με το NetworkX της Python: Μια προκαταρκτική (αλλά ημιτελής ω...
 
Go a crash course
Go   a crash courseGo   a crash course
Go a crash course
 

Similar to Alta performance com Python

Writing Faster Python 3
Writing Faster Python 3Writing Faster Python 3
Writing Faster Python 3
Sebastian Witowski
 
Python 3
Python 3Python 3
Python 3
Andrews Medina
 
Scaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approachScaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approach
Jinal Jhaveri
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in Ruby
Larry Diehl
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
Oon Arfiandwi
 
Go on!
Go on!Go on!
Go on!
Vadim Petrov
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
ConFoo
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
Guy Komari
 
Os lab final
Os lab finalOs lab final
Os lab final
LakshmiSarvani6
 
COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?
Lloyd Huang
 
Process monitoring in UNIX shell scripting
Process monitoring in UNIX shell scriptingProcess monitoring in UNIX shell scripting
Process monitoring in UNIX shell scripting
Dan Morrill
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
André Faria Gomes
 
03 Geographic scripting in uDig - halfway between user and developer
03 Geographic scripting in uDig - halfway between user and developer03 Geographic scripting in uDig - halfway between user and developer
03 Geographic scripting in uDig - halfway between user and developer
Andrea Antonello
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
niklal
 
Commit2015 kharchenko - python generators - ext
Commit2015   kharchenko - python generators - extCommit2015   kharchenko - python generators - ext
Commit2015 kharchenko - python generators - ext
Maxym Kharchenko
 
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbsSystem Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
ashukiller7
 
What the CRaC - Superfast JVM startup
What the CRaC - Superfast JVM startupWhat the CRaC - Superfast JVM startup
What the CRaC - Superfast JVM startup
Gerrit Grunwald
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
WebSummit 2015 - Gopher it
WebSummit 2015 - Gopher itWebSummit 2015 - Gopher it
WebSummit 2015 - Gopher it
Gautam Rege
 

Similar to Alta performance com Python (20)

Writing Faster Python 3
Writing Faster Python 3Writing Faster Python 3
Writing Faster Python 3
 
Python 3
Python 3Python 3
Python 3
 
Scaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approachScaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approach
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in Ruby
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
 
Go on!
Go on!Go on!
Go on!
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
Os lab final
Os lab finalOs lab final
Os lab final
 
COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?COSCUP2012: How to write a bash script like the python?
COSCUP2012: How to write a bash script like the python?
 
Process monitoring in UNIX shell scripting
Process monitoring in UNIX shell scriptingProcess monitoring in UNIX shell scripting
Process monitoring in UNIX shell scripting
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
03 Geographic scripting in uDig - halfway between user and developer
03 Geographic scripting in uDig - halfway between user and developer03 Geographic scripting in uDig - halfway between user and developer
03 Geographic scripting in uDig - halfway between user and developer
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
 
Commit2015 kharchenko - python generators - ext
Commit2015   kharchenko - python generators - extCommit2015   kharchenko - python generators - ext
Commit2015 kharchenko - python generators - ext
 
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbsSystem Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
 
What the CRaC - Superfast JVM startup
What the CRaC - Superfast JVM startupWhat the CRaC - Superfast JVM startup
What the CRaC - Superfast JVM startup
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
WebSummit 2015 - Gopher it
WebSummit 2015 - Gopher itWebSummit 2015 - Gopher it
WebSummit 2015 - Gopher it
 

Recently uploaded

Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
kalichargn70th171
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Undress Baby
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
lorraineandreiamcidl
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Envertis Software Solutions
 

Recently uploaded (20)

Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
 

Alta performance com Python

  • 2. Alta Performance com Python Paralelismo e Concorrência BrunoBarbosa Desenvolvedor de Software na Globo.com Há 7 anos escrevendo software profissionalmente Programador por diversão há 14 anos Apaixonado por Python e todo seu ecossistema Trabalhando atualmente na maior parte do tempo com Python, Go e JavaScript. Iniciou sua carreira trabalhando com Python, Zope e Plone Brasiliense se aventurando pelo errejota :)
  • 3.
  • 7. ThreadsProcessos Compartilham memória Custo de spawn/switch Necessidade de recursos Mecanismos de sincronização Processos Threadse Comparativo
  • 8. PROCESSO1 DADOS COMPARTILHADOS PELASTHREADS THREAD1 THREAD2 THREAD3 DADOS DADOS DADOS Processos Threadse Anatomia de um processo
  • 9. PROCESSO1 PROCESSO2 DADOS COMPARTILHADOS PELASTHREADS THREAD THREAD THREAD DADOS DADOS DADOS DADOS COMPARTILHADOS PELASTHREADS THREAD THREAD THREAD DADOS DADOS DADOS Processos Threadse Anatomia de um processo
  • 11. CPUBOUND I/OBOUND Processos Threadse Tipos de processos Computações matemáticas intensas Algoritmos de busca e ordenação em memória Processamento e reconhecimento de imagem Transferência de dados pela rede Escrita de arquivo em disco Consulta a uma API HTTP ConcorrênciaParalelismo
  • 15. O famigerado GIL (Global Interpreter Lock)
  • 16.
  • 17. import multiprocessing import os import threading import time MAX_WORKERS = 4
 
 def io_expensive(sleep_time=1): """ Do nothing, wait for a timer to expire """ print("PID: {}, Process Name: {}, Thread Name: {}".format( os.getpid(), multiprocessing.current_process().name, threading.current_thread().name) ) time.sleep(sleep_time) Simulando uma atividade de rede I/O Bound
  • 18. Simulando uma atividade de rede I/O Bound 1ºTeste:Sequencial import time from main_example import MAX_WORKERS, io_expensive
 
 start_time = time.time() for i in range(MAX_WORKERS): io_expensive(i) end_time = time.time() print("n✔ Serial time=", end_time - start_time)
  • 19. Simulando uma atividade de rede I/O Bound 2ºTeste:Threads import time from concurrent import futures from main_example import MAX_WORKERS, io_expensive start_time = time.time() with futures.ThreadPoolExecutor(MAX_WORKERS) as executor: executor.map(io_expensive, range(MAX_WORKERS)) end_time = time.time() print("n✔ Threads time=", end_time - start_time)
  • 20. Simulando uma atividade de rede I/O Bound 2ºTeste:Threads import time from concurrent import futures from main_example import MAX_WORKERS, io_expensive start_time = time.time() with futures.ThreadPoolExecutor(MAX_WORKERS) as executor: executor.map(io_expensive, range(MAX_WORKERS)) end_time = time.time() print("n✔ Threads time=", end_time - start_time)
  • 21. Simulando uma atividade de rede I/O Bound 3ºTeste:Processos import time from concurrent import futures from main_example import MAX_WORKERS, io_expensive start_time = time.time() with futures.ProcessPoolExecutor() as executor: executor.map(io_expensive, range(MAX_WORKERS)) end_time = time.time() print("n✔ Parallel time=", end_time - start_time)
  • 22. Simulando uma atividade de rede I/O Bound 3ºTeste:Processos import time from concurrent import futures from main_example import MAX_WORKERS, io_expensive start_time = time.time() with futures.ProcessPoolExecutor() as executor: executor.map(io_expensive, range(MAX_WORKERS)) end_time = time.time() print("n✔ Parallel time=", end_time - start_time)
  • 23. Simulando uma atividade de rede I/O Bound
  • 24. import multiprocessing import os import threading import time MAX_WORKERS = 4
 
 def cpu_expensive(): """ Do some computations """ print("PID: {}, Process Name: {}, Thread Name: {}".format( os.getpid(), multiprocessing.current_process().name, threading.current_thread().name) ) x = 0 while x < 10000000: x += 1 Simulando uma atividade de alto processamento CPU Bound
  • 25. 1ºTeste:Sequencial import time from main_example import MAX_WORKERS, cpu_expensive
 
 start_time = time.time() for i in range(MAX_WORKERS): cpu_expensive() end_time = time.time() print("n✔ Serial time=", end_time - start_time) Simulando uma atividade de alto processamento CPU Bound
  • 26. 2ºTeste:Threads import time from concurrent import futures from main_example import MAX_WORKERS, cpu_expensive start_time = time.time() with futures.ThreadPoolExecutor(MAX_WORKERS) as executor: for _ in range(MAX_WORKERS): executor.submit(cpu_expensive) end_time = time.time() print("n✔ Threads time=", end_time - start_time) Simulando uma atividade de alto processamento CPU Bound
  • 27. Simulando uma atividade de rede I/O Bound 2ºTeste:Threads import time from concurrent import futures from main_example import MAX_WORKERS, cpu_expensive start_time = time.time() with futures.ThreadPoolExecutor(MAX_WORKERS) as executor: for _ in range(MAX_WORKERS): executor.submit(cpu_expensive) end_time = time.time() print("n✔ Threads time=", end_time - start_time)
  • 28. 3ºTeste:Processos import time from concurrent import futures from main_example import MAX_WORKERS, io_expensive start_time = time.time() with futures.ProcessPoolExecutor() as executor: for _ in range(MAX_WORKERS): executor.submit(cpu_expensive) end_time = time.time() print("n✔ Parallel time=", end_time - start_time) Simulando uma atividade de alto processamento CPU Bound
  • 29. Simulando uma atividade de rede I/O Bound 3ºTeste:Processos import time from concurrent import futures from main_example import MAX_WORKERS, io_expensive start_time = time.time() with futures.ProcessPoolExecutor() as executor: for _ in range(MAX_WORKERS): executor.submit(cpu_expensive) end_time = time.time() print("n✔ Parallel time=", end_time - start_time)
  • 30. Simulando uma atividade de alto processamento CPU Bound
  • 32. E O TAL DO ASYNC/AWAIT?
  • 33.
  • 35. Produzindo valores através de yield Generators def gen_integer(): print("Calling for fist time""...") yield 1 print("Calling for second time""...") yield 2 print("Calling for third time""...") yield 3 "">>> next(gen) Calling for fist time… 1 "">>> next(gen) Calling for second time… 2 "">>> gen = gen_integer() "">>> next(gen) Calling for third time… 3 Traceback (most recent call last): ""... StopIteration "">>> next(gen)
  • 36. Produzindo valores através de yield Generators def gen_fruit(): fruits = ['apple', 'banana', 'grape'] for fruit in fruits: yield fruit "">>> basket = gen_fruit() "">>> for fruit in basket: print(f"Got: {fruit}") Got: apple Got: banana Got: grape
  • 37. Usando yield from Generators def gen_fruit(): fruits = ['apple', 'banana', 'grape'] for fruit in fruits: yield fruit "">>> basket = gen_fruit() "">>> for fruit in basket: print(f"Got: {fruit}") Got: apple Got: banana Got: grape def gen_fruit(): fruits = ['apple', 'banana', 'grappes'] yield from fruits
  • 39. Coroutines Um gerador melhorado def example_coro(): print("""--> Execution started") x = yield print(f"""--> Received value: {x}") def main(): coro = example_coro() print("""==> Preparing the coroutine""...") next(coro) print("""==> sending a value to coroutine: ") coro.send(42)
  • 40. ""==> Preparing the coroutine… ""--> Execution started ""==> sending a value to coroutine: ""--> Received value: 42 Traceback (most recent call last): ""... StopIteration Coroutines Um gerador melhorado
  • 41. Coroutines Um gerador melhorado def example_coro_2(start_num): print("""--> Example started!") value = yield start_num print(f"""--> Received: {value}") yield start_num + value def example_2(): coro = example_coro_2(20) initial_value = next(coro) print(f"""==> Initial value: {initial_value}") v = coro.send(22) print(f"""==> sum: {v}") next(coro)
  • 42. ""--> Example started! ""==> Initial value: 20 ""--> Received: 22 ""==> sum: 42 Traceback (most recent call last): ""... StopIteration Coroutines Um gerador melhorado
  • 44. ASYNC / AWAIT Código assíncrono através de corrotinas import asyncio import time @asyncio.coroutine def say_after(delay, what): yield from asyncio.sleep(delay) print(what) @asyncio.coroutine def main(): print('started at', time.strftime('%X')) yield from say_after(1, 'hello') yield from say_after(2, 'world') print('finished at', time.strftime('%X')) asyncio.run(main())
  • 45. ASYNC / AWAIT Código assíncrono através de corrotinas import asyncio import time async def say_after(delay, what): await asyncio.sleep(delay) print(what) async def main(): print('started at', time.strftime('%X')) await say_after(1, 'hello') await say_after(2, 'world') print('finished at', time.strftime('%X')) asyncio.run(main())
  • 46. ASYNC / AWAIT Fazendo requisições HTTP com o método aiohttp import aiohttp import asyncio async def fetch(session, url): async with session.get(url) as response: return await response.text() async def main(): async with aiohttp.ClientSession() as session: html = await fetch(session, 'http:"//python.org') print(html) loop = asyncio.get_event_loop() loop.run_until_complete(main())