Skip to content

Instantly share code, notes, and snippets.

@rougeth
Created April 21, 2018 20:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rougeth/70d0efd922a5f1a689696546260d3a1b to your computer and use it in GitHub Desktop.
Save rougeth/70d0efd922a5f1a689696546260d3a1b to your computer and use it in GitHub Desktop.
Async que se faz - TDC 2018
# Código usado na palestra "Async que se faz - asyncio na prática"
# no TDC 2018 em Florianópolis
# Creative Commons Attribution 4.0 International license <https://creativecommons.org/licenses/by/4.0/>
# requirements: termcolor
import random
import asyncio
from asyncio import sleep as async_sleep
from time import time, sleep as sync_sleep
from termcolor import colored
API_RESPONSE_TIME = [0.1] * 3 + [0.4] * 4 + [1] * 2 + [10]
UPDATE_AVG = [True] + [False] * 9
def show(s, t):
if t == 0.1:
color = 'cyan'
elif t == 0.4:
color = 'white'
elif t == 1:
color = 'yellow'
else:
color = 'red'
print(colored(s, color))
def sync_request(pedido, api):
t = random.choice(API_RESPONSE_TIME)
show('>>> {}: {} request'.format(pedido, api), t)
sync_sleep(t)
show('<<< {}: {} response in {}s'.format(pedido, api, t), t)
async def async_request(pedido, api):
t = random.choice(API_RESPONSE_TIME)
show('>>> {}: {} request'.format(pedido, api), t)
await async_sleep(t)
show('<<< {}: {} response in {}s'.format(pedido, api, t), t)
async def timeit(f):
start = time()
await asyncio.wait([f])
print('Tempo de execução:')
print(colored('{:.2f} segundos'.format(time()-start), 'grey', 'on_green'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment