Created
July 1, 2021 07:55
-
-
Save ZenithClown/df4391a8b0313eb808e9a0f4ef5c78ad to your computer and use it in GitHub Desktop.
A Simple Python Decorator Function to Print the Runtime of a Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding: utf-8 -*- | |
__author__ = "Debmalya Pramanik" | |
__status__ = "production" | |
__version__ = "1.0" | |
__docformat__ = "camelCasing" | |
__copyright__ = "Copyright (c) 2020 Debmalya Pramanik | Indian Institute of Technology (IIT), Dhanbad" | |
__affiliation__ = "Reliance Industries Ltd." | |
import time | |
import functools | |
def timeit(func): | |
"""Inspired from `timeit` this Decorator Calculates the Execution time of a Function | |
Usage - Use as a Decorator `@timeit` as follows: | |
```python | |
@timeit | |
def some_function(): | |
# do some work | |
some_function() # execute the function with the decorator | |
> Run time for some_function: **** | |
``` | |
""" | |
@functools.wraps(func) | |
def _wrapper(*args, **kwargs): # accepts all arguments | |
start = time.time() | |
_return = func(*args, **kwargs) # execute the actual function | |
end = time.time() # function executed, time is calculated with ms precision | |
# calculate execution time is seconds (if t > 0), else in ms | |
_exce_time = f"{(end - start):0.2f} s" if int(end - start) > 0 else f"{(end - start)*1e3:0.2f} ms" | |
print(f"Run time for {func.__name__}: {_exce_time}") | |
return _return | |
return _wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment