Created
April 1, 2018 04:14
-
-
Save agronick/2522172701316cb36318a96833b1bbac to your computer and use it in GitHub Desktop.
CPU Bound code runs 3x-5x slower with asyncio
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 | |
loop = asyncio.new_event_loop() | |
def print_time(): | |
global start | |
end = time.time() | |
print(end - start) | |
async def fib(n): | |
if 2 > n: | |
return n | |
return (await fib(n-2)) + (await fib(n-1)) | |
async def go(): | |
global start | |
for _ in range(50): | |
start = time.time() | |
print(await asyncio.gather(*[fib(i) for i in range(1, 25)])) | |
print_time() | |
loop.run_until_complete(go()) | |
loop.close() | |
end = time.time() | |
print(end - start) | |
"""" | |
Here is the last few lines of output for this code. The non async version runs between 0.04 and 0.06 seconds: | |
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368] | |
0.12500882148742676 | |
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368] | |
0.12501978874206543 | |
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368] | |
0.12501168251037598 | |
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368] | |
0.12500548362731934 | |
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368] | |
0.12500834465026855 | |
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368] | |
0.12501192092895508 | |
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368] | |
0.12500500679016113 | |
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368] | |
0.10938239097595215 | |
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368] | |
0.12502384185791016 | |
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368] | |
0.12500524520874023 | |
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368] | |
0.12500858306884766 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment