How to measure function execution time in Python

1 Answer

0 votes
# Measuring function execution time in 
# Python using a reusable Timer (milliseconds + seconds)

import time

# ---------------------------
# Reusable Timer class
# ---------------------------
class Timer:
    def __init__(self):
        self.start = 0.0
        self.end = 0.0

    # Start the timer
    def start_timer(self):
        self.start = time.perf_counter()  # high‑precision timer

    # Stop the timer
    def stop_timer(self):
        self.end = time.perf_counter()

    # Return elapsed time in milliseconds
    def elapsed_milliseconds(self):
        return (self.end - self.start) * 1000.0

    # Return elapsed time in seconds
    def elapsed_seconds(self):
        return self.end - self.start


# ---------------------------
# Function to measure
# ---------------------------
def work():
    s = 0
    for i in range(100_000_000):
        s += i


# ---------------------------
# Main program
# ---------------------------
if __name__ == "__main__":
    t = Timer()

    t.start_timer()
    work()
    t.stop_timer()

    ms = t.elapsed_milliseconds()
    sec = t.elapsed_seconds()

    print("Execution time:", ms, "ms")
    print("Execution time:", sec, "seconds")



"""
run:

Execution time: 5462.636256999986 ms
Execution time: 5.462636256999986 seconds

"""

 



answered 1 hour ago by avibootz
...