Skip to content

Instantly share code, notes, and snippets.

@tcwalther
Created May 13, 2016 13:58
Show Gist options
  • Save tcwalther/be174615eee7dec9ffb1a8d32c540345 to your computer and use it in GitHub Desktop.
Save tcwalther/be174615eee7dec9ffb1a8d32c540345 to your computer and use it in GitHub Desktop.
from functools import wraps
import timeit
from config import logger
from contextlib import contextmanager
@contextmanager
def measure_time_to(message):
"""
Logs the time it takes to execute the block inside the with statement.
Params
------
message:
string to display in the log. Log message will be:
"Took X.XXXs to [MESSAGE]"
Example
-------
> with measure_time_to("restore session %d" % session.id):
> session.restore()
Output, via logger.info():
"Took 1.311s to restore session 21"
"""
start_time = timeit.default_timer()
yield
elapsed = timeit.default_timer() - start_time
logger.info('Took %1.3fs to %s' % (elapsed, message))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment