Skip to content

Instantly share code, notes, and snippets.

@aeros
Last active October 17, 2019 07:44
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 aeros/b328f04f15af68543466f41dc2be118a to your computer and use it in GitHub Desktop.
Save aeros/b328f04f15af68543466f41dc2be118a to your computer and use it in GitHub Desktop.
Benchmark to compare the performance of asyncio.get_running_loop() and asyncio.get_event_loop() within a coroutine.
import asyncio
import time
total_tests = 10_000_000
async def test_get_running_loop():
return asyncio.get_running_loop()
async def test_get_event_loop():
return asyncio.get_event_loop()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
start = time.monotonic_ns()
for _ in range(total_tests):
loop.run_until_complete(test_get_running_loop())
end = time.monotonic_ns()
get_running_time = end - start
start = time.monotonic_ns()
for _ in range(total_tests):
loop.run_until_complete(test_get_event_loop())
end = time.monotonic_ns()
get_event_time = end - start
get_running_avg = get_running_time / total_tests
get_event_avg = get_event_time / total_tests
print(f"Average execution time from {total_tests} tests:")
print(f"get_running_loop: {get_running_avg} nanoseconds")
print(f"get_event_loop: {get_event_avg} nanoseconds")
@aeros
Copy link
Author

aeros commented Oct 11, 2019

Tested on:
Python version: Python 3.9.0a0 (heads/master:320dd504dd, Oct 10 2019, 19:19:18)
OS: Arch Linux 5.3.1
CPU: Intel i5-4460

Average execution time from 10,000,000 tests:
get_running_loop: 22149.6837362 nanoseconds
get_event_loop: 22198.1162637 nanoseconds

From the above results, asyncio.get_running_loop() is slightly faster than asyncio.get_event_loop() within a coroutine.

Although the performance difference is negligible, the benefit of using asynio.get_running_loop() is that its behavior is significantly more explicit and easier to understand. See the documentation for details.

@aeros
Copy link
Author

aeros commented Oct 17, 2019

Tested on:
Python version: Python 3.7.4
OS: Arch Linux 5.3.1
CPU: Intel i5-4460

Average execution time from 10,000,000 tests:
get_running_loop: 22696.8933876 nanoseconds
get_event_loop: 22724.0467757 nanoseconds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment