Skip to content

Instantly share code, notes, and snippets.

@ajdavis
Created February 21, 2014 21:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajdavis/9143996 to your computer and use it in GitHub Desktop.
Save ajdavis/9143996 to your computer and use it in GitHub Desktop.
Count current greenlet's CPU cost
import gevent
# GreenletProfiler 0.1 from https://pypi.python.org/pypi/GreenletProfiler
import GreenletProfiler
MILLION = 1000 * 1000
def print_greenlet_cpu_time():
# Find self in list of "thread stats", actually greenlet stats.
greenlet_id = id(gevent.getcurrent())
for stat in GreenletProfiler.get_thread_stats():
if stat.id == greenlet_id:
print stat.sched_count, stat.ttot
break
def foo():
for i in range(20 * MILLION):
if not i % (2 * MILLION):
gevent.sleep(0)
print 'foo done'
def bar():
for i in range(10 * MILLION):
if not i % MILLION:
gevent.sleep(0)
print_greenlet_cpu_time()
print 'bar done'
GreenletProfiler.set_clock_type('cpu')
GreenletProfiler.start()
foo_greenlet = gevent.spawn(foo)
bar_greenlet = gevent.spawn(bar)
foo_greenlet.join()
bar_greenlet.join()
GreenletProfiler.stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment