Skip to content

Instantly share code, notes, and snippets.

@jbower-fb
Created September 30, 2022 22:46
Show Gist options
  • Save jbower-fb/b52d40bec31d578cadc643b5bad8a485 to your computer and use it in GitHub Desktop.
Save jbower-fb/b52d40bec31d578cadc643b5bad8a485 to your computer and use it in GitHub Desktop.
Benchmark for prototype TaskGroup.enqueue() vs. TaskGroup.create_task()
# Sample output from my development machine:
# taskgroup_create_task(nop, nop): 4.584088109433651
# taskgroup_enqueue(nop, nop): 0.5685205422341824
# 8.06x improvement
# taskgroup_create_task(zero_sleep, zero_sleep): 5.616343416273594
# taskgroup_enqueue(zero_sleep, zero_sleep): 4.856606440618634
# 1.16x improvement
# taskgroup_create_task(small_sleep, small_sleep): 8.519412336871028
# taskgroup_enqueue(small_sleep, small_sleep): 8.220038397237659
# 1.04x improvement
# taskgroup_create_task(nop, zero_sleep): 5.269423408433795
# taskgroup_enqueue(nop, zero_sleep): 3.498860226944089
# 1.51x improvement
# taskgroup_create_task(nop, small_sleep): 6.990674836561084
# taskgroup_enqueue(nop, small_sleep): 5.217445608228445
# 1.34x improvement
import asyncio
from timeit import timeit
async def nop():
pass
async def zero_sleep():
await asyncio.sleep(0)
async def small_sleep():
await asyncio.sleep(0.00000001)
async def taskgroup_create_task(op1, op2):
for _ in range(50000):
async with asyncio.TaskGroup() as tg:
tg.create_task(op1())
tg.create_task(op1())
tg.create_task(op2())
tg.create_task(op2())
async def taskgroup_enqueue(op1, op2):
for _ in range(50000):
async with asyncio.TaskGroup() as tg:
tg.enqueue(op1())
tg.enqueue(op1())
tg.enqueue(op2())
tg.enqueue(op2())
for op1, op2 in [
(nop, nop),
(zero_sleep, zero_sleep),
(small_sleep, small_sleep),
(nop, zero_sleep),
(nop, small_sleep)]:
t1 = timeit(lambda: asyncio.run(taskgroup_create_task(op1, op2)), number=2)
print(f"taskgroup_create_task({op1.__name__}, {op2.__name__}): {t1}")
t2 = timeit(lambda: asyncio.run(taskgroup_enqueue(op1, op2)), number=2)
print(f"taskgroup_enqueue({op1.__name__}, {op2.__name__}): {t2}")
print(f"{t1/t2:.2f}x improvement")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment