To get values from the generator object, call the next() method on the generator object or loop through the generator object.
Introduction to the profilers cProfile and profile provide deterministic profiling of Python programs. A profile is a set of statistics that describes how often and for how long various parts of the program executed. These statistics can be formatted into reports via the pstats module.
Generators are memory efficient since they only require memory for the one value they yield. Generators are lazy: they only yield values when explicitly asked.
Python generators are a simple way of creating iterators. All the work we mentioned above are automatically handled by generators in Python. Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).
I'm adapting an application that makes heavy use of generators to produce its results to provide a web.py web interface.
So far, I could wrap the call to the for-loop and the output-producing statements in a function and call that using cProfile.run()
or runctx()
. Conceptually:
def output():
for value in generator():
print(value)
cProfile.run('output()')
In web.py, I have to wrap it the following way, since I want to immediately produce output from the potentially long-running computation in each iteration step using yield
:
class index:
def GET(self):
for value in generator():
yield make_pretty_html(value)
Is there a way to profile all calls to the generator like in the first example when it's used like in the second one?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With