Три способа выполнить множество задач с asyncio
Функция для примера:
async def do_it(n):
await asyncio.sleep(random.uniform(0.5, 1))
return n
1. Последовательный вызов
async def main():
for i in range(100):
result = await do_it(i)
Такой вызов имеет смысл только тогда, когда результат одной задачи требуется для вызова следующей.
Если они независимы, то это антипаттерн, так как аналогичен простому синхронному вызову по очереди.
2. Упорядоченный результат
async def main():
tasks = [do_it(i) for i in range(100)]
results = await asyncio.gather(*tasks)
Выполняет корутины конкурентно и возвращает результат в виде списка.
Полезен когда требуется получить результаты в том же порядке в котором задачи отправлены.
3. Результат по мере готовности
tasks = [asyncio.create_task(do_it(i)) for i in range(100)]
for cor in asyncio.as_completed(tasks):
result = await cor
Так же выполняет корутины конкурентно, но не гарантирует порядок. Результат возвращается по мере готовности, каждый отдельно.
Полезен когда нужно обработать любой ответ как можно скорее.
#async
"I'm rose without it's essence,
I'm a bouquet of autumn leaves,
I'm a tree without it's texture,
I'm glass without it's fragility,
I'm a sidewalk without grafitti,
A plain white coral,
I'm a scenery without a painter,
You see;
I still exist without you,
But It's not beautiful..."
#review#nilu
🔥 Дизайнер Александр Селипанов, основавший автомобильный бренд Nilu27, рассекретил суперкар Nilu
Интерьер — смесь минимализма и футуризма. Физических кнопок практически нет — лишь на потолке имеются переключатели в авиационном стиле. При этом тачскринов в салоне суперкара тоже нет: единственный дисплей встроен в зеркало заднего вида.
Базируется автомобиль на углепластиковом монококе с трубчатыми подрамниками, имеет полностью независимую подвеску и 21-дюймовые колёсные диски с карбон-керамическими тормозами Brembo с шестипоршневыми суппортами.
Атмосферный 6,5-литровый V12 развивает 1070 л.с. и 860 Нм, что позволяет разгоняться до максимальных 400 км/ч и набирать первую сотню быстрее чем за 3 секунды.
Полноценная премьера состоится 15 августа. Сначала сделают 15 машин для гоночных трасс, а уже потом выпустят 54 купе для дорог общего пользования.
@avtoNovosti
#новинки#суперкар#Nilu
🔥 Designer Alexander Selipanov, who founded the car brand Nilu27, has declassified the Nilu supercar
The interior is a mix of minimalism and futurism. There are practically no physical buttons - only on the ceiling there are switches in aviation style. At the same time, there are no touchscreens in the interior of the supercar either: the only display is built into the rearview mirror.
The car is based on a carbon fiber monocoque with tubular subframes, has a fully independent suspension and 21-inch wheels with Brembo carbon-ceramic brakes with six-piston calipers.
Atmospheric 6.5-liter V12 develops 1070 hp and 860 Nm, which allows to accelerate to a maximum of 400 km/h and gain the first hundred faster than 3 seconds.
The full-fledged premiere will take place on August 15. First, 15 cars will be made for race tracks, and then 54 coupes for public roads will be released.
@CarsNews
#new#supercar#Nilu
🚗✨Introducing the Nilu Supercar by Alexander Selipanov!🔥
Designed for true driving enthusiasts, the Nilu is a masterpiece that strips away unnecessary electronics to deliver pure driving pleasure. 🏁💨
🔩Powerful Performance:
Equipped with a breathtaking atmospheric V12 engine producing 1070 hp, paired with a 7-speed manual transmission. This beast can reach a top speed of 400 km/h and accelerate from 0 to 100 km/h in under 3 seconds! ⚡️
⚙️Cutting-Edge Engineering:
Built on a carbon fiber monocoque with tubular subframes, featuring fully independent pushrod suspension and 21-inch wheels with carbon-ceramic brakes. 🛠️
🚢Exclusive Release:
Only 15 units will be produced for track enthusiasts, followed by another 54 road-ready models. Pricing details remain under wraps! 💰
#Nilu#Supercar#AlexanderSelipanov#DrivingPassion#V12#Auto