Source code for pylib.helper
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Helper objects.
:Date: 2020-01-01
.. module:: helper
:platform: *nix, Windows
:synopsis: Helper objects.
.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
"""
import time
from contextlib import ContextDecorator
[docs]class timeit(ContextDecorator):
"""Meassure time for a function or code block.
:param description: description for the function or code block
used for the print-out
:type description: str
:Example:
>>> with timeit('section_test'):
... # code
section_test took 0.006 ms
::
@timeit('func')
def func():
# code
>>> func()
func took 0.006 ms
"""
def __init__(self, description=None):
self.description = description
def __enter__(self):
self.start_time = time.time()
return self # to use as: with Timit() as t:
def __exit__(self, *exc): # exc: type, value, traceback
elapsed_time_ms = (time.time() - self.start_time) * 1000
print('{:s} took {:.3f} ms'.format(self.description, elapsed_time_ms))
return False