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.
import timeit
def test_function():
return sum(range(100))
# Measure the execution time of the function
execution_time = timeit.timeit(test_function, number=1000)
print(f"Execution time: {execution_time} seconds")
import timeit
setup_code = "from math import sqrt"
test_code = "sqrt(25)"
# Measure the execution time
execution_time = timeit.timeit(test_code, setup=setup_code, number=100000)
print(f"Execution time: {execution_time} seconds")
import timeit
# List of code snippets
codes = [
"sum(range(100))",
"max(range(100))",
"min(range(100))"
]
# Measure execution time for each code
for code in codes:
execution_time = timeit.timeit(code, number=1000)
print(f"Execution time for {code}: {execution_time} seconds")
import timeit
code1 = "sum(range(100))"
code2 = "reduce(lambda x, y: x + y, range(100))"
# Measure execution times for both
time_code1 = timeit.timeit(code1, number=10000)
time_code2 = timeit.timeit(code2, number=10000)
print(f"Execution time for code1: {time_code1} seconds")
print(f"Execution time for code2: {time_code2} seconds")
import timeit
class TestClass:
def method1(self):
return sum(range(100))
def method2(self):
return max(range(100))
# Instantiate the class
test_instance = TestClass()
# Measure execution times for class methods
execution_time1 = timeit.timeit(test_instance.method1, number=1000)
execution_time2 = timeit.timeit(test_instance.method2, number=1000)
print(f"Execution time for method1: {execution_time1} seconds")
print(f"Execution time for method2: {execution_time2} seconds")
import timeit
code = "sum(range(100))"
# Repeat the timing 5 times and get the best result
execution_times = timeit.repeat(code, number=1000, repeat=5)
print(f"Execution times: {execution_times}")
print(f"Best execution time: {min(execution_times)} seconds")
import timeit
# Example of processing a large dataset
setup_code = "data = list(range(1000000))"
test_code = "sum(data)"
# Measure execution time
execution_time = timeit.timeit(test_code, setup=setup_code, number=10)
print(f"Execution time: {execution_time} seconds")
import timeit
# Assuming the function is defined in a separate file 'my_code.py'
execution_time = timeit.timeit("from my_code import my_function; my_function()", number=100)
print(f"Execution time: {execution_time} seconds")