Last active
October 11, 2018 06:41
-
-
Save ods/257d442e75423309b2b7dd1d106599d7 to your computer and use it in GitHub Desktop.
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 time, asyncio, hashlib | |
def sync_cpu_bound(): | |
s = bytes(range(256)) | |
for i in range(100000): | |
hashlib.sha256(s) | |
start = time.time() | |
sync_cpu_bound() | |
calc_time = time.time() - start | |
async def c0(): | |
t = asyncio.Task(tf('c0')) | |
await asyncio.sleep(calc_time) | |
t.cancel() | |
async def c1(): | |
t = asyncio.Task(tf('c1')) | |
await asyncio.sleep(0) | |
sync_cpu_bound() | |
await asyncio.sleep(0) | |
t.cancel() | |
async def c2(): | |
t = asyncio.Task(tf('c2')) | |
await l.run_in_executor(None, sync_cpu_bound) | |
t.cancel() | |
@asyncio.coroutine | |
def tf(name): | |
c = 0 | |
try: | |
while True: | |
c += 1 | |
yield | |
except asyncio.CancelledError: | |
print(f'[debug={l.get_debug()}] count for {name}: {c}') | |
raise | |
l = asyncio.new_event_loop() | |
for debug in [False, True]: | |
l.set_debug(debug) | |
l.run_until_complete(c0()) | |
l.run_until_complete(c1()) | |
l.run_until_complete(c2()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment