Absolutely, and I agree with @jacqueline-bosco on the simplicity of time.time()
. However, for more precise measurements, especially when you’re timing small durations or testing multiple functions, I recommend using time.perf_counter()
instead it provides a higher resolution. To make it cleaner, you can wrap the timing code in a decorator:
import time
def time_it(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"{func.__name__} took {end - start:.6f} seconds")
return result
return wrapper
@time_it
def my_function():
print("hello")
my_function()
This way, you’re keeping your code reusable and elegant, and it works well if you’re testing multiple functions in your project.