How to Create a Named Timer in Python?

Estimated read time 2 min read

To create a named timer in Python, you can define a class that contains the necessary functionality. Here is an example:

import time

class Timer:
    def __init__(self, name):
        self.name = name
        self.start_time = None
        self.elapsed_time = None

    def start(self):
        self.start_time = time.time()

    def stop(self):
        if self.start_time is None:
            raise ValueError("Timer must be started before it can be stopped")
        self.elapsed_time = time.time() - self.start_time

    def get_elapsed_time(self):
        if self.elapsed_time is None:
            raise ValueError("Timer must be stopped before the elapsed time can be retrieved")
        return self.elapsed_time

In this example, we define a Timer class that has a name attribute to identify the timer, a start_time attribute to store the time at which the timer was started, and an elapsed_time attribute to store the time between when the timer was started and stopped. The start method sets the start_time attribute to the current time, and the stop method calculates the elapsed time and stores it in the elapsed_time attribute. The get_elapsed_time method returns the elapsed time if the timer has been stopped, or raises a ValueError if the timer has not yet been stopped.

Here is an example of how to use the Timer class:

# Create a timer
t = Timer("My Timer")

# Start the timer
t.start()

# Do some work
time.sleep(2)

# Stop the timer
t.stop()

# Get the elapsed time
print("Elapsed time:", t.get_elapsed_time())

This will output the elapsed time in seconds.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply