Last active
January 1, 2016 05:58
-
-
Save pydong/8101662 to your computer and use it in GitHub Desktop.
Comparison between gevent synchronous calls and asynchronous calls
1) synchronous() # next task is blocked until current one is finished
2) asynchronous() #all start @ the same time
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
| # based on http://sdiehl.github.io/gevent-tutorial/ | |
| import gevent | |
| import random | |
| start = time.time() | |
| tic = lambda: 'at %1.1f seconds' % (time.time() - start) | |
| def task(pid): | |
| """ | |
| Some non-deterministic task | |
| """ | |
| secs = random.randint(0, 10) | |
| gevent.sleep(secs) | |
| print('Task %s done in [ %s ] seconds' % (pid, secs)) | |
| def synchronous(): | |
| print('Started synchronous: %s' % tic()) | |
| for i in range(1,10): #runs one by one, gevent sleeps when the task runs | |
| task(i) | |
| print('Ended synchronous: %s' % tic()) | |
| def asynchronous(): | |
| print('Started asynchronous: %s' % tic()) | |
| threads = [gevent.spawn(task, i) for i in xrange(10)] #runs "at the same time", gevent sleeps "at the same time" | |
| gevent.joinall(threads) | |
| print('Ended asynchronous: %s' % tic()) | |
| print('Synchronous:') | |
| synchronous() | |
| print('Asynchronous:') | |
| asynchronous() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment