How to time a function in python (bonus: intervals ⏱️)

Method 1: use time.time() and do calculations

Python
import time

def my_function():
    # Your function code here
    time.sleep(1)  # Example function that sleeps for 1 second

start_time = time.time()
my_function()
end_time = time.time()

elapsed_time = end_time - start_time

# Check if elapsed time is greater than a minute
if elapsed_time > 60:
    minutes = elapsed_time // 60
    seconds = elapsed_time % 60
    print(f"mod took {int(minutes)} minutes and {seconds:.2f} seconds to complete.")
else:
    print(f"mod took {elapsed_time:.2f} seconds to complete.")

Method 2: Create a Timer class that stores the start time and last time recorded

Python
import time

class Timer:
    def __init__(self):
        now = time.time()
        self.start_time = now
        self.last_checkpoint = now

    def _print(self, seconds, name="time"):
        minutes = int(seconds // 60)
        seconds = seconds % 60
        print(f"{name}: {minutes}:{seconds:.2f}")
        
    def print_elapsed_time(self):
        now = time.time() 
        from_start = now - self.start_time
        from_last = now - self.last_checkpoint
        
        self._print(from_start, "Elapsed from start: ")
        self._print(from_last, "Interval from last: ")
        
        self.last_checkpoint = now
        
        

# Usage example
timer = Timer()

for i in range(100):
    timer.print_elapsed_time()