Last active
December 15, 2017 08:33
-
-
Save clarksun/6de88e96b2c678980a9cf3245ce10ae2 to your computer and use it in GitHub Desktop.
gevent #python #gevent
This file contains hidden or 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 gevent | |
import random | |
import time | |
from functools import wraps | |
# http://sdiehl.github.io/gevent-tutorial/ | |
def task(pid): | |
""" | |
Some non-deterministic task | |
""" | |
gevent.sleep(random.randint(0, 2)) | |
print('Task %s done' % pid) | |
def elapsed(func): | |
@wraps(func) | |
def wrapped(*args, **kwargs): | |
t1 = time.time() | |
func(*args, **kwargs) | |
t2 = time.time() - t1 | |
print(f'used:{t2}') | |
return wrapped | |
@elapsed | |
def synchronous(): | |
for i in range(1, 10): | |
task(i) | |
@elapsed | |
def asynchronous(): | |
threads = [gevent.spawn(task, i) for i in range(20000)] | |
gevent.joinall(threads) | |
print('Synchronous:') | |
synchronous() | |
print('Asynchronous:') | |
asynchronous() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment