Skip to content

Instantly share code, notes, and snippets.

@methane
Created April 3, 2012 16:28
Show Gist options
  • Select an option

  • Save methane/2293384 to your computer and use it in GitHub Desktop.

Select an option

Save methane/2293384 to your computer and use it in GitHub Desktop.
Measure the cost of greenlet switching.
import gevent
import sys
N = int(sys.argv[1])
M = int(sys.argv[2])
def sleeper(n):
for i in xrange(N):
#print(n)
gevent.sleep(0)
def sleeper2(n):
hub = gevent.get_hub()
idle = hub.loop.idle(1)
wait = hub.wait
for i in xrange(N):
#print(n)
wait(idle)
greenlets = [gevent.spawn(sleeper2, i) for i in xrange(M)]
gevent.joinall(greenlets)
@methane

methane commented Apr 3, 2012

Copy link
Copy Markdown
Author

In my environment,

$ time python switchbench.py 1000 1000
real    0m11.314s
user    0m11.241s
sys 0m0.056s

@methane

methane commented Apr 3, 2012

Copy link
Copy Markdown
Author

sleeper2 inlined gevent.sleep(). This makes significant speedup.

$ time python switchbench.py 1000 1000
real    0m7.891s
user    0m7.844s
sys 0m0.032s

Real Python application has more Python code. So the cost of greenlet switching is small relatively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment