Ir al contenido principal

First approach to the python3.6 async programming, a simple consumer/producer (async programming with python 3.6 step 1)

As a first approach to the async programming I'm developing small scripts with python.


The main thing I need to learn is how to develop an asynchronous consumer/producer using an async Queue and python3.6.

First, a reproduction of the problem with synchronous programming, later the solution I found with async programming.

Synchronous


# First attempt, synchronous

from queue import Queue
from time import sleep, perf_counter


def produce(q: Queue, n: int):
    for i in range(n):
        print(f'produce {i}')
        q.put(i)
        sleep(0.1)


def consume(q: Queue):
    for i in q.queue:
        print(f'consume {i}')
        sleep(0.1)


start = perf_counter()
q = Queue()
produce(q, 10)
consume(q)
print(perf_counter() - start)


# Output

produce 0
produce 1
produce 2
... # imagin that
consume 7
consume 8
consume 9
2.005685806274414

It takes about 2 seconds

Asynchronous

# Second attempt, Asynchronous

import asyncio
from time import perf_counter


async def produce(queue: asyncio.Queue, n: int):
    for x in range(n):
        print(f'produce {x}')
        await asyncio.sleep(0.1)
        await queue.put(x)


async def consume(queue: asyncio.Queue):
    while True:
        x = await queue.get()
        print(f'consume {x}')
        await asyncio.sleep(0.1)
        queue.task_done()


async def run(n: int = 10):
    queue = asyncio.Queue()
    consumer = asyncio.ensure_future(consume(queue))

    await produce(queue, n)
    await queue.join()

    consumer.cancel()



start = perf_counter()
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
loop.close()
print(perf_counter() - start)

# Output

produce 0
produce 1
consume 0
produce 2
consume 1
produce 3
...
consume 7
produce 9
consume 8
consume 9
1.1065495014190674

It takes 1.10 seconds, pretty much better, no?

Comentarios

Entradas populares de este blog

Join o producto cartesiano de dos tablas en EXCEL 2007

Hace unos dias inicie mi ocupacion como becario de informatica en la facultad de humanidades y ciencias de la educacion de la UJAEN. Y como no, no han tardado en surgir los problemas. Supongamos que tenemos dos tablas, y queremos hacer una tabla que tenga datos de estas dos tablas, segun un criterio , y es que solo pueden aparecer ciertas filas, mas exactamente aquellas donde coincida cierto campo, en este ejemplo, el codigo de la asignatura. Si queremos realizar el join o producto cartesiano tal y como lo hariamos en una base de datos, parece ser que si no estamos trabajando con una bbdd sino con Excel, la cosa se complica un poco. Para "multiplicar tablas" en excel, primero vamos a hacer una cosa, cada tabla la vamos a guardar en hojas separadas, en nuestro caso, una tabla la guardamos en Hoja1 , y la otra en Hoja2 Ahora, nos situamos en la hoja donde queramos que aparezca el producto cartesiano de nuestras dos tablas, nos vamos a la ficha DATOS . Veremos que h...

Use django ORM standalone within your nameko micro-services

Learning about micro services with python, I found a great tool named nameko . https://www.nameko.io/ Nameko is a Python framework to build microservices that doesn't care in concrete technologies you will use within your project. To allow that microservices to work with a database, you can install into your project a wide variety of third parties, like SQLAlchemy (just like any other). To have an easy way to communicate with the database and keep track of the changes made to the models, I chose Django: I'm just learning about microservices and I want to keep focused on that. Easy to use, Django is a reliable web framework, have a powerful and well known ORM. Also using Django we will have many of the different functionalities that this framework provide. To make all this magic to work together, I developed a python package that allow you to use Django as a Nameko injected dependency: https://pypi.org/project/django-nameko-standalone/ You can found the source ...

Polynomial regression using python

We are going to learn how to create a polynomial regression and make a prediction over a future value using python. The data set have been fetched from INE (national statistics institute) , that data is the EPA ( active population survey ), that tell us the national total (Spain), both genders. 16 and over are unemployed ( in thousands ). Example data: label serie rate 0 2002T1 0 2152.8 1 2002T2 1 2103.3 2 2002T3 2 2196.0 3 2002T4 3 2232.4 4 2003T1 4 2328.5 Data CSV can be downloaded here: https://drive.google.com/file/d/1fwvAZe7lah5DX8-DDEpmfeUDYQhKcfzG/view?usp=sharing Lets see how looks that data: Fine, as we can see the data describe a curve, so its for that because we want to use a polynomial regression. To try to approximate that curve we will use a grade 2 polynomial or...