109. Performance Tuning with timeit

The timeit module in Python is designed for measuring the execution time of small code snippets. It helps you to identify performance bottlenecks and optimize your code by providing accurate measurements.

Here are 10 code snippets to demonstrate different use cases of timeit:

1. Basic Usage of timeit

To measure the execution time of a simple Python expression, use timeit.timeit().

Copy

import timeit

# Measure the execution time of a simple code snippet
execution_time = timeit.timeit('sum(range(100))', number=1000)
print(f"Execution time: {execution_time} seconds")

Explanation:

  • number=1000 specifies how many times the code should run.

  • This will execute sum(range(100)) 1000 times and give you the total time.


2. Using timeit with a Lambda Function

You can also use timeit to measure the performance of a lambda function.

Copy

import timeit

# Using a lambda function
execution_time = timeit.timeit(lambda: sum(range(100)), number=1000)
print(f"Execution time: {execution_time} seconds")

3. Measuring Code in a Function

You can use timeit to measure the execution time of an entire function.

Copy


4. Setting up Code Context with setup Parameter

You can pass setup code that will be run once before the test code starts running.

Copy

Explanation:

  • The setup parameter ensures that the math.sqrt function is imported before running the test code.


5. Using timeit in a Loop

You can measure the time of multiple code snippets by looping through them.

Copy


6. Comparing Multiple Code Snippets

You can compare the performance of two code snippets by using timeit to measure each one.

Copy

Explanation:

  • This example compares the performance of sum() versus reduce() for summing a range of numbers.


7. Measuring Time for Code in a Class

You can also measure the performance of methods inside a class.

Copy


8. Using timeit with repeat()

You can repeat the timing multiple times to get a better idea of the average time.

Copy

Explanation:

  • repeat runs the code multiple times and returns a list of execution times.

  • You can take the best execution time by using min().


9. Measuring Time of a Large Dataset Operation

You can measure the time of more complex operations like processing a large dataset.

Copy


10. Timeit in an External File

You can use timeit to measure code inside a separate file.

Copy


Key Points:

  • timeit.timeit(): Measures the execution time of a code snippet.

  • setup: Optional parameter to set up the environment before running the code.

  • repeat(): Repeats the test multiple times and returns the execution times for each.

  • number: Specifies how many times the code should run.

  • min(): Can be used to get the best execution time when using repeat().

By using timeit, you can easily measure the performance of small pieces of code and optimize your applications accordingly.

Last updated