Last active
October 17, 2019 07:44
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
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
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 thanasyncio.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.