Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

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 May 27 by avibootz
...