Skip to content

Instantly share code, notes, and snippets.

@CodeByAidan
Created May 9, 2023 23:36
Show Gist options
  • Select an option

  • Save CodeByAidan/e83a4b2c68fa67df6ae2678ea27fdef4 to your computer and use it in GitHub Desktop.

Select an option

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!
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