prometheus / client_python

Prometheus instrumentation library for Python applications
Apache License 2.0
3.97k stars 797 forks source link

Timing generator function #843

Open samipdahalr opened 2 years ago

samipdahalr commented 2 years ago

Is there any way to time how long it takes to execute a generator function in python with Histogram.time? Right now, it only seems to measure the time to get the generator object. But since generators do lazy computation while actually iterating over it, we don't get full time.

Example:

def generate_n(n):
    for i in range(n):
        yield i
jaklaassen-affirm commented 2 years ago

I think you should be able to do this with a context manager.

def generate_n(n):
   with hist.time():
      for i in range(n):
          yield i

Unless I'm quite mistaken... I didn't actually test it, but I do think that should work.