Created
April 12, 2024 18:24
-
-
Save estevaofon/2a358f91b23bdde3fe0adba27d49a182 to your computer and use it in GitHub Desktop.
Decorator to log execution time of functions
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
import time | |
import functools | |
def log_time(func): | |
"""Decorator to log the execution time of a function.""" | |
@functools.wraps(func) | |
def wrapper(*args, **kwargs): | |
start_time = time.time() # Capture the start time | |
result = func(*args, **kwargs) # Execute the function | |
end_time = time.time() # Capture the end time | |
execution_time = end_time - start_time # Calculate the execution time | |
print(f"{func.__name__} executed in {execution_time:.4f} seconds") | |
return result | |
return wrapper | |
# Example of using the decorator | |
@log_time | |
def sample_function(x): | |
"""Function to simulate some processing.""" | |
time.sleep(x) # Simulate time delay with sleep | |
return x * x | |
# Running the function to see the decorator in action | |
result = sample_function(2) | |
print("Result:", result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment