What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Timeit in Python: Example, Function & Arguments (Easy Guide)

  • Mar 31, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Kusum Jain
Timeit in Python: Example, Function & Arguments (Easy Guide)

An essential part of becoming a professional coder is the ability to optimize your code. There is a module that can be used to efficiently code by reducing time complexity. Let’s learn how timeit works in python below.

What is timeit in Python?

Python's timeit module is used to measure the execution time of smaller pieces of code. It provides a basic method for benchmarking by timing how long it takes to run the code. Monitoring execution time is vital in software development since it allows you to increase the efficiency of your code.

A single line of code, a block of code, or a whole function can be measured for time using the timeit module. It has various timing techniques to assure high accuracy, as well as choosing the number of iterations to run. The module also lets you pause garbage collection during timing, which can significantly boost timing accuracy for code snippets. 

You can also compare the execution times of different code snippets or algorithms to see which one is quicker. This is important when dealing with huge datasets or during computationally intensive tasks, where little improvements in execution time might result in a significant performance improvement.

An Example

Let us consider the example below to understand the timeit module better. Consider making a pattern below using python programming, there are multiple ways to code it.

Case 1: We can execute it using nested loops 

import timeit 
def pattern(number):
    for i in range(0, number):
         
        
            for j in range(0, i+1):
             
           
                print("* ",end="")
          
            
            print("\r")
number = 5

print(timeit.timeit(lambda: pattern(number), setup="pass",number=1))

 

Output:

* 
* *
* * *
* * * *
* * * * *
0.0019884999928763136

 

Case 2: using a single for loop

import timeit 
def pattern(n):
    list = []
    for i in range(1,n+1):
        list.append("*"*i)
    print('\n'.join(list))
number = 5

print(timeit.timeit(lambda: pattern(number), setup="pass",number=1))

 

Output:

* 
* *
* * *
* * * *
* * * * *
0.0009992999985115603

 

We can see that case 2 has a significantly lower run time, hence for optimization, we would use code in case 2. 

Is Python Timeit in seconds?

The python timeit method is by default measuring in seconds but it can be specified to measure in milliseconds, microseconds, or minutes. Its result is usually a floating-point number with a high level of precision depending on the platform.

Python's timeit function & its arguments

In Python, the timeit function is used to time the execution of a statement or a function. It requires three arguments: 'stmt', setup' and 'number'.

The syntax for the function:

timeit.timeit(stmt, setup, timer, number)

Let us understand each argument in depth.

  • stmt: The stmt parameter specifies the statement or function to time. A string containing a single line of code or a function object can be used. When timing a function, you must supply the function object rather than the function call.
  • setup: The setup parameter is a statement or function that is run before the timed statement or function. It prepares the environment for the timed statement or function. You may use the setup parameter to import any modules or declare any variables that the function needs while timing it.
  • number: The optional number parameter defines the number of times the statement or function is to be run. The default setting is 1. To obtain more precise timing results, you can change the number of iterations.

By specifying these arguments correctly, you can get accurate timing results for any statement or function and optimize your code for performance.

Where can we use timeit()?

Here are a few use cases and practical applications of the timeit function:

  1. Comparing two distinct implementations of the same algorithm: when you have two separate sorting algorithm implementations and want to implement the quicker one, One can use timeit to time each implementation and compare the results to figure out which is faster. 
  2. Evaluating a function's performance: If a function is taking too long to run, you can use timeit to pinpoint the elements of the function that are causing the delay. You might find bottlenecks and optimize the program for improved performance.
  3. Testing the efficiency of regular expressions: Regular expressions can be computationally expensive, and if you are working with large amounts of text data, you may need to optimize your regular expressions for performance

Conclusion

We learned in this guide about the timeit module in Python with an example. It is a flexible tool that may be used to evaluate the efficacy of programs in various scenarios. We also discussed the function, its arguments and where to use it.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Kusum Jain
I am an avid coder on CodeChef, I partake in hackathons regularly. I am an independent and self-motivated student with a love for coding and experiencing new things.