Understanding the Python Timer Class with Examples

Python has thousands of modules and libraries to satisfy the coder’s demands. However, to make them useful, you have to understand them first and then apply them. Without the prior knowledge of certain modules, it’s uncertain what you want to do and what the module actually does. Time is one of the important factors in coding problems. All the codes are meant to reduce human work by using their powerful algorithms. Time management creates a great impact on the analysis of the performance of your code. That’s why today, we will learn in-depth about how the timer works in Python.

Python Timer is a class/library to manage the time complexity of your code. Using multiple time modules, you can create a system in your code to check the time taken by the respective code snippet. There are different types of timer implementations in python according to user needs, namely, python timer function (to check script execution time), python threading timer (to check the time taken by a thread to finish), python countdown timer (create a countdown timer) and basic python time module (to help with other activities).

All of these timer implementation functions differently and focuses on providing different use to the end-user. In this post, we’ll go through every timer implementation in detail. You can use the Table of Contents to jump to the respective python timer implementation.

Basic Python Timer Functions

The most important module in python regarding time is time. This module contains all the basic functions to check the time and analyze it. This analysis will help you to understand the performance of your code and its efficiency. We’ll go through each of the important functions from this module along with its examples.

Following are the basic Python Timer functions using the time module –

Function time.time

time.time() returns the time in seconds (float) after the epoch. Generally, the epoch is set to January 1, 1970, 00:00:00 (UTC), and the number of seconds after this epoch is returned. This function depends on the computer time for calculating the number of seconds. If you change the computer time between the python execution, you can get weird numbers using this function.

Example –

import time

start = time.time() #start time

for i in range(1000000):
    pass

end = time.time()
print("Elapsed time is  {}".format(end-start))

Explanation –

Firstly, we start with importing the time module. This module contains all the basic time functions which we’ll use in this section. At the start of the code, we’ll declare the start variable as time.time(). This will store the current time of CPU in float number from the epoch. We’ll use this start variable as a reference point to measure the time. The next part contains all the codes you want to use (In this example, we’ve used a for loops). Similarly, record the end time of the CPU (Default time) and check the total execution time by using end – start.

This will print the time taken by the code in seconds. With the use of this technique, you can check the time taken by your code. The only problem with this method is that the CPU time can be changed while the code is running. This will result in problematic behavior in python timer.

Function time.Thread_time

time.thread_time() returns the sum of system and CPU time (float) in the current running thread. Moreover, it doesn’t include the time you spend in time.sleep() function. As the function is thread-specific, you can use this function to record the time differences as long as the time references belong to the same thread.

Example –

import time
import threading
end = None
start = None
def hello():
    global start, end
    start = time.thread_time()
    x = 0 
    while x < 10000000:
        pass
        x += 1
    end = time.thread_time()

t = threading.Thread(target = hello, args = ())
t.start() 
t.join()

print("The time spent is {}".format(end - start))

Explanation –

As the thread_time returns thread-specific time, we have to make sure to use references in the same thread. For this purpose, we’ve instantiated the thread of function ‘hello‘ and calculated the time taken by the thread inside it. However, make sure that you cannot get the current time by calling thread_time() because it returns a fractional value. But you can definitely check the difference between two consecutive references as long as they belong in the same thread.

Function time.Process_time

time.process_time() returns the time reference in fractional seconds (float) of the sum of system time and CPU time of current progress. Same as thread_time, this function doesn’t measure the time spent in time.sleep() function. Moreover, this function creates a reference based on the process. As a result of this, only the time difference between two consecutive references will make sense.

Example –

from time import process_time, sleep

iterations = 100000

start = process_time()  
   
for i in range(iterations):
    print(i, end=" ")
  
# Stop the stopwatch / counter 
end = process_time()
print(end, start)
print("Elapsed time in seconds:", end-start)

Explanation –

We start with importing the process_time function and record the start and end time between the code. The only difference between legacy time.time() and time.proces_time() is that the processing time records the time references of the current process, whereas time() records the system’s absolute time.

Function time.Perf_counter

Perf Counter stands for Performance Counter. This function returns the high-resolution value of the time, which is valid for a short period of time. This function is used to get the precise time count between two references. As other python timer functions don’t include sleep time, perf_counter also doesn’t include it. Let’s move to an example –

Example –

from time import perf_counter, sleep
  
# integer input from user, 2 input in single line
n = 3
  
# Start the stopwatch / counter 
start = perf_counter()  
  
for i in range(n): 
    sleep(1)

end = perf_counter() 
  
  
print("Elapsed time in seconds:", end-start) 

Explanation –

You can use the perf counter in the same way as the process timer or thread timer. The only difference is, perf counter will return a high precise value of the time elapsed. But make sure that you use this between small processes, as it uses high precision. We’ve used a simple loop to check the time taken by it.

Function time.monotonic

Monotonic is a python timer that cant go backward. When executing a python script, the time can be changed by the user and can make a huge difference in the implementation of the timer in python. But monotonic timer ensures that the time references adjust to the external changes.

Example –

from time import monotonic, sleep
  
# integer input from user, 2 input in single line
n = 3
  
# Start the stopwatch / counter 
start = monotonic()  
  
for i in range(n): 
    sleep(1)

end = monotonic() 
  
  
print("Elapsed time in seconds:", end-start) 

Explanation –

We first import the monotonic function from the time module. Then create two references named start and end in the top and bottom side of the code. This will measure the time between the two references and avoid all the external changes to the system times.

Custom Python Timer Classes

You can create your own custom Timer class to do things according to your need. One main advantage of creating a custom class is you can manage all the time in a single line. You don’t need to import the time class every time and record the references. Moreover, you can dump your data and record all the past time executions to choose the best algorithm for you.

This section will create a custom class to manage the time and log all the time differences in your codes. Let’s dive right into it –

Timer.py –

We’ll begin with importing the time module. Then initialize the python Timer class and start defining the attributes and methods. So far, we’ve only included the basic attribute to keep a start reference of the class. To make it more complex, you can create multiple attributes. So far, there are three methods listed below –

  1. start – (Optional) To start the timer.
  2. log – To log the current elapsed time concerning start time.
  3. milestone – To reset the timer and start its count from 0.
import time

class Timer:

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

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

    def log(self):
        logger = time.time() - self.start
        print('Time log -',logger)

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

example.py –

Examples of usage of the above class are given below. As you can view, you can keep your code clean by creating a custom Timer class and increase flexibility.

import timer

time = timer.Timer()
for i in range(1000000):
	pass
	p = 1
time.log()
for i in range(1000000):
	pass
	p = 1
time.log()

Output –

Time log - 0.054854631423950195
Time log - 0.10871052742004395

Python Timer using Threading

When we want to perform some operation or want our function to run after a certain amount of time, we make use of the Python Timer class. The timer class is a subclass of the threading class. Technically, you can say that we create Timer objects when we want actions (functions) bounded by the time. 

 For example, suppose we want to organize a quiz, where the participant has to answer each question in 10 seconds. Here, we can create a timer that will run in the background, and meanwhile, the participant will be thinking about the answer. Now, let us understand how to create a timer object

Syntax of Timer Class in Python

If you have not understood what Timer class does, you can think of it in this way – A Timer Class calls a function after the specified number of seconds.  

To start a timer, we need to call the start()(just like normal threads), and to stop the timer while it is still in the background, we can call cancel()

To use the Timer class, we need to import threading class  

threading.Timer(interval, function, args=None, kwargs=None) 

Parameters-  

Interval– The time (in seconds) you want to wait before calling the next function. It can either be in float or integer. For example, for 3 seconds, interval=3. 

Function – The function you want to call after the specified interval of time. 

A pervasive way to describe *args and **kwargs parameters is- create a timer object that runs the function with arguments’ args’ and keyword arguments’ kwargs’ after interval seconds have passed. Args should be in the form of a list and0 keyword args or kwargs in the form of a dictionary

Return Type- 

It just calls the function specified in the parameters. 

Methods in Timer class 

  1. start() – It signifies the beginning of execution of the timer. 
  2. Cancel ()– During the timer’s execution, we can call the cancel if we want to stop it (). 

Creating a Timer Object 

a. Understanding the basics

To understand the Timer object’s working, let us create a small program to help us understand the class’s basics. 

# Importing the Timer subclass from the threading Class
from threading import Timer

# creating a basic function that will print "hello"
def hello():
    print ("hello, world")

# creating the object of the Timer subclass
# Here, 5 sec means that the execution of the function="hello" after 5 seconds
t = Timer(interval=5.0, function=hello)

# starting the execution
t.start() # after 30 seconds, "hello, world" will be printed
Output-
hello, world
python timer

You will better understand the functioning of the above program when you try to run it on your own system.

b. Using the cancel method

Let us see how to use the cancel() function of Timer class.

# Importing the Timer subclass from the threading Class
from threading import Timer

# creating a basic function that will print "hello"
def hello():
    print ("hello world")
    
# creating the object of the Timer subclass
# Here, 5 sec means that the execution of the function="hello" after 5 seconds
t = Timer(interval=5.0, function=hello)
    
# starting the execution
t.start() # after 30 seconds, "hello, world" will be printed

print("Execution begins")

# cancelling the execution of the 'hello' function
t.cancel()
print("END")
Execution begins 
END

c. How to use the ‘args’ parameter of the python timer class

When we need to give the arguments to the function that needs to be called, we use the args parameter. We must give the args argument in an array.

import threading

# To take multiple inputs we can use *before the parameter.
def print_name(*names):
    # From the array of names pick one name and print it
    for name in names:
        print("Hello",name)

# In the args parameter, give an array of names 
t = threading.Timer(3, print_name,["Ashwini","Vandy","Arijit"])

# start the execution
t.start()
print("Execution begins...")
Execution begins...
Hello Ashwini
Hello Vandy
Hello Arijit

Now that we have talked a lot about time, as a bonus, let us make a program which will act as a Countdown Timer.

Countdown Timer in python

Using the time module

# We will use the time module
import time

# Create a function that will print the time
def create_countdown_timer(time):
    print(time,"......")

time_in_sec=int(input("Please entert the time in seconds:"))

for times in range(time_in_sec):
    # call the function and pass the current time left
    create_countdown_timer(time_in_sec-times)
    # call the function in every 1 second.
    time.sleep(1)
    
print("Time is up")
Please entert the time in seconds:7
7 ......
6 ......
5 ......
4 ......
3 ......
2 ......
1 ......
Time is up

Using the python Timer Class

# We will use the time module
import time

from threading import Timer

# Create a function that will print the time
def create_countdown_timer(time):
    print(time,"......")

# Here you have to enter the time for which the timer will run
time_in_sec=int(input("Please enter the time in seconds:"))

# For the first time we will call the function manually
create_countdown_timer(time_in_sec) 

for times in range(1,time_in_sec): 
    # calling the Timer class every second
    t = Timer(1,create_countdown_timer,[str(time_in_sec-times)])
    t.start()
    time.sleep(1)
    
print("\n Time is up")
    
Please entert the time in seconds:10
10 ......
9 ......
8 ......
7 ......
6 ......
5 ......
4 ......
3 ......
2 ......
1 ......
Time is up

Python Timers as Context Managers

Context Managers are the best ways to avoid memory errors and subsequent crashes. Everyone must’ve known about “with” the statement in Python. This statement ensures that we don’t have to take care of many objects to close independently. Everyone might have used it with the combination of with and open() function. So, moving to the main question, can we create Context Managers for Python Timers?

Yes. Due to multiple overloading functions, we can easily create our own python timer as a context manager in just a few lines. Let’s start with an example where you have to measure the program’s time to run. Without redefining all the variables, one context manager can be used repeatedly to measure the time multiple times. The following program demonstrates it.

Example –

import time


class Timer_Pythonpool():
    """
        Context manager as a python timer
    """
    def __init__(self): 
        self.start = None
          
    def __enter__(self):
        """
            Notes the time at the start of the iteration
        """
        self.start = time.time()
        return self
      
    def __exit__(self, exc_type, exc_value, exc_traceback):
        """
            Prints the time taken at the end of the iteration
        """
        print("Time to finish the task: ", time.time()-self.start)
  
  
with Timer_Pythonpool() as timer: 
    for i in range(1000000):
        x = 0
        pass

Output –

Time to finish the task:  0.05392050743103027

Explanation –

We start by creating a class named “Timer_Pythonpool.” Then we customize the operators to make them useful as a context manager. __enter__ function executes at the start of the context, and __exit__ executes at the end of context. Creating a reference point between these two functions can give you the exact time taken by the context to execute.

Python Timer Decorators

Decorators are the additional support for any kind of function. Also termed as metaprogramming, you can modify/add functionality to it. Python Timer Decorators are the easiest way to implement the timer functions in python. Once declared, you can use the decorators in one line without even knowing them. Adding to it, you can apply them to every function in your code to check which code takes the most time to execute.

Syntax –

To create a chaining decorator, you need to declare multiple nested functions. Name the other function as your main decorator name and inner to any random name. The inner function will fetch the reference of the function used below the decorator.

Example –

import time

def check_time(func):
    def inner(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        end = time.time()
        print("Time taken to execute function is ", end-start)
    return inner


@check_time
def task():
    # do something
    for i in range(10000000):
        x = 0
        pass


task()

Output –

Time taken to execute function is  0.24933218955993652

Explanation –

As usual, we start with importing the most important module from python “time.” Nextly, we create a decorator named “check_time.” Inside it, we add a nested inner function where we can create the references of time. These two references are placed so that both of them are placed between the function execution.

Further, we create a testing function named “task” to check if our task works. Then add a decorator on top of it. Now the decorator will do its magic and print the time taken by the function.

Python Timer Cooldown

Python Timer Cooldown is a way to measure the timer backward. By creating a custom timer class, we can log the time at every point of your code. You can export this class as a module and install it as a dependency in your code. Then by using a single line, you can import it –

import time

class Timer:
    """
        Timer class
    """
    def __init__(self):
        self.start = time.time()

    '''
    Restarts the timer.
    '''
    def restart(self):
        self.start = time.time()


    '''
    Returns the time elapsed and resets the counter.
    '''
    def get_new_time(self):
        value = time.time() - self.start
        self.restart()
        return value


    '''
    Prints the time elapsed and resets the counter.
    '''
    def print_new_time(self):
        print (self.get_new_time())


    '''
    Returns the time elapsed (Does not reset the counter).
    '''
    def get_time(self):
        return time.time() - self.start
        self.restart()


    '''
    Prints the time elapsed (Does not reset the counter).
    '''
    def print_time(self):
        print(self.get_time())


    '''
    Returns the time elapsed in HH:mm:ss (Does not reset the counter).
    '''
    def get_time_hhmmss(self):
        end = time.time()
        m, s = divmod(end - self.start, 60)
        h, m = divmod(m, 60)
        time_str = "%02d:%02d:%02d" % (h, m, s)
        return time_str


timer = Timer() #Initialize the timer
#wash clothes for 5 seconds
timer.print_time() #Print the time elapsed since Initialization (in seconds)
#dry clothes for 3 seconds
timer.print_new_time() #Print the time elapsed since Initialization and reset the timer
#burn clothes for 10 seconds
print(str('Task done for ' + str(timer.get_time()) + ' seconds.'))

Other Python Timer Modules

Python contains thousands of modules and millions of code snippets. We can always use the open-source modules to use python timers. Github is the biggest place to find such modules. Let’s jump right into these modules –

  1. termdown: An advanced python timer made by using different ASCII characters. Using this script, you can create a simple countdown timer in your terminal and execute a command at the end. Most importantly, it has support for voice countdown.
  2. MobTimer.Python: A GUI based timer made in python. This script creates full screen-based timers with multiple options. Along with it, you can run multiple timers on your screen at the same time by using this program.
  3. timer: This is the most basic GUI based timer made in python (Tkinter). Features like multiple timers, labels, and multithreading make it more viable over other programs.
  4. codetiming: This timer class records all your past execution times for a specific named process. You can check the minimum time, maximum time, meantime, and median time for the specific process along with records. This module can be used in multiple ways, namely, as a context manager and as a decorator.
  5. cTimer: cTime is a nanosecond-precision timer in python. This module uses the c language API to record the time precisely. If you’re looking for a hardcore precision time recording modules, this is the best one. (Note: In recent updates of python, the time module is added with functions to record time in nanoseconds)

Must Read:

Conclusion

Mostly, everyone uses timers for three purposes. The first one being, to record the time for your code execution. And second one being, to add a reminder for something by using a timer. Fortunately, both of these can be created in Python. By using different modules and libraries, you can ensure that you record the time with pinpoint accuracy.

Last but not the least, The timer is a subclass of the threading Class in python. If we want to run any function after a certain interval of time, we can use the python timer class. In the args parameter, which is None by default, we can specify the arguments we want to give to the callback method.

Try to run the programs on your side and let us know if you have any queries.

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments