Created
May 9, 2023 23:36
-
-
Save CodeByAidan/e83a4b2c68fa67df6ae2678ea27fdef4 to your computer and use it in GitHub Desktop.
Decorator Example in Python. Creating a timeit-like function decorator. Simple and Easy!
This file contains hidden or 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
| import time | |
| from functools import wraps | |
| class timeit: | |
| def __init__(self, func=None, verbose=False): | |
| self.verbose = verbose | |
| self.func = func | |
| wraps(func)(self) | |
| def __call__(self, *args, **kwargs): | |
| if self.verbose: | |
| print(f"Running '{self.func.__name__}'...") | |
| start_time = time.perf_counter() | |
| result = self.func(*args, **kwargs) | |
| end_time = time.perf_counter() | |
| elapsed_time = end_time - start_time | |
| if self.verbose: | |
| print(f"'{self.func.__name__}' completed.") | |
| print(f"'{self.func.__name__}' executed in {elapsed_time:.6f} seconds.") | |
| return result | |
| def __get__(self, instance, owner): | |
| return self if instance is None else self.__class__(self.func.__get__(instance, owner), self.verbose) | |
| def verbose_timeit(func): | |
| return timeit(func, verbose=True) | |
| @timeit | |
| def example_function(n): | |
| sum = 0 | |
| for i in range(n): | |
| sum += i | |
| return sum | |
| example_function(1000000) | |
| @verbose_timeit | |
| def example_function_verbose(n): | |
| sum = 0 | |
| for i in range(n): | |
| sum += i | |
| return sum | |
| example_function_verbose(1000000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment