Skip to content

Instantly share code, notes, and snippets.

@odedlaz
Created November 28, 2016 12:06
Show Gist options
  • Save odedlaz/7811f703cc30a9d266817eaa4014ba7a to your computer and use it in GitHub Desktop.
Save odedlaz/7811f703cc30a9d266817eaa4014ba7a to your computer and use it in GitHub Desktop.
from __future__ import print_function
import gc
import sys
import time
class TimeIt(object):
def __init__(self, scope_name="", fd=sys.stdout):
self._start = None
self._fd = fd
self._fmt = 'block took {{secs:.5f}} seconds to run [{}]'.format(scope_name)
def __enter__(self):
# run the garbage collector
# then disable it so it won't tamper with the measurments
gc.collect()
gc.disable()
self._start = time.time()
def __exit__(self, exc_type, exc_val, exc_tb):
now = time.time() - self._start
print(self._fmt.format(secs=now).strip(), file=self._fd)
# enable garbage collection after we're done with measurments
gc.enable()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment