Display Code Execution Time

The following code example is from Decorators in Python || Python Tutorial (YouTube)

Watch the complete video for a detailed information.

Description of How It Works

# ---- define a function that will be used as a decorator def decorator_demo(func): def inner_function(*args,**kargs): ~~~~~ some code ~~~~~ return inner_function # ---- modify the behavior of the "work" function (f) using # ---- the decorator @decorator_demo def f(x,y,z): ~~~~ some code ~~~~ # ---- Note: when you call the function (f) Python executes # ---- decorator_demo(f)(x,y,z)

Code Example

#!/usr/bin/python3 # ========================================================= # Use defined decorator - display code execution time # ========================================================= import time # --------------------------------------------------------- # timer decorator - display code execution time # --------------------------------------------------------- def timer(f): def wrapper(*args,**kargs): start_time = time.perf_counter() ##start_time = time.time() results = f(*args,**kargs) stop_time = time.perf_counter() ##stop_time = time.time() dt = stop_time - start_time print(f'dt = {dt}') return results return wrapper # --------------------------------------------------------- # here we use the "timer" decorator to wrap the # function prime_factorization # --------------------------------------------------------- @timer def prime_factorization(n): factors = [] divisor = 2 while n > 1: while n % divisor == 0: factors.append(divisor) n //= divisor divisor += 1 return factors # --------------------------------------------------------- # here we execute the function "prime_factorization" which # is wrapped by the "timer" decorator # ---- # when executing "prime_factorization" the "timer" function # steps in front of the call and returns the function # "wrapper" which is then executed. "wrapper" executes # "prime_factorization" and displays its execution time. # --------------------------------------------------------- results = prime_factorization(2**29+1) print(results)