Context managers are objects that define the runtime context to be established when executing a with statement.
In Python, we can define our own Timer context manager object, which we can then use in order to time specific sections of our code without too detrimental an impact on our codebase.
This time, the context manager object will look something this:
from timeit import default_timer
class Timer(object):
def __init__(self, verbose=False):
self.verbose = verbose
self.timer = default_timer
def __enter__(self):
self.start = default_timer()
return self
def __exit__(self, *args):
end = default_timer()
self.elapsed_secs = end - self.start
self.elapsed = self.elapsed_secs * 1000 # millisecs
if self.verbose:
print('elapsed time: %f ms' % self.elapsed)
We define a Timer class which features a constructor, an entry point, and an exit point. Upon entry, we start the Timer, and upon exit, we calculate the elapsed time.
We can then utilize this class like this within our Python programs:
from timer import Timer
from urllib.request import Request, urlopen
import ssl
def myFunction():
# We create this context so that we can crawl
# https sites
myssl = ssl.create_default_context()
myssl.check_hostname=False
myssl.verify_mode=ssl.CERT_NONE
with Timer() as t:
req = Request('https://tutorialedge.net', headers={'User-Agent': 'Mozilla/5.0'})
response = urlopen(req, context=myssl)
print("Elapsed Time: {} seconds".format(t.elapsed))
myFunction()