Example: Timing Block Execution - 4.3.2 | Chapter 4: Context Managers and the with Statement | Python Advance
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Academics
Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Professional Courses
Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skillsβ€”perfect for learners of all ages.

games

Code block to measure

sum([i for i in range(100000)])
end = time.time()

print(f"Execution time: {end - start} seconds")
Using the timeit Module
The timeit module is more accurate as it minimizes the impact of background tasks and system calls by running the code multiple times.

Example:
python
Copy
Edit
import timeit

execution_time = timeit.timeit("sum([i for i in range(1000)])", number=1000)
print(f"Total time for 1000 runs: {execution_time} seconds")
You can also use timeit with a function:

python
Copy
Edit
def test():
return sum([i for i in range(1000)])

print(timeit.timeit(test, number=1000))
Custom Context Manager for Timing
You can build your own context manager to time any block of code using with.

python
Copy
Edit
import time

class Timer:
def enter(self):
self.start = time.time()
return self

def __exit__(self, *args):
    self.end = time.time()
    self.interval = self.end - self.start
    print(f"Time taken: {self.interval} seconds")

with Timer():
sum([i for i in range(100000)])
This method is elegant and reusable.

Real-Life Analogy
Timing execution is like using a stopwatch for athletes. You hit start before the run and stop after. Just like that, Python lets you mark your start and end to calculate the performance of code.

Memory Aid
Mnemonic: β€œStart-End = Time Spent”

Story: Think of racing toy cars. You click β€œstart” when the car begins and β€œstop” when it finishes β€” just like start = time.time() and end = time.time().

Glossary
time module: Provides simple functions for tracking time.

timeit module: Measures execution time with high precision.

Context Manager: A Python construct that manages resources using enter and exit.

Estimated Study Time
10 minutes


Exercises
Easy
Question: What module provides a quick and simple way to measure execution time?

Answer: time

Hint: It's the same name as what you're measuring.

Question: What function gives the current time in the time module?

Answer: time.time()

Hint: Think of it as asking Python β€œwhat time is it?”

Medium
Question: How would you measure the time taken to run a function 1000 times using timeit?

Answer: Use timeit.timeit(func, number=1000)

Hint: You need to repeat it and then record the total time.

Question: What’s the benefit of using timeit over time.time()?

Answer: timeit gives more accurate results by minimizing startup overhead and background noise.

Hint: Think about precision and consistency.

Hard
Question: Create a context manager that prints how long a code block took to execute.

Answer:

import time
class Timer:
def enter(self):
self.start = time.time()
return self
def exit(self, *args):
self.end = time.time()
print(f"Time: {self.end - self.start}")
Hint: Use enter and exit methods.

Question: Explain how timeit.timeit() avoids inaccurate results due to background processes.

Answer: It runs the code multiple times to average out random variations and reduces noise from system calls.

Hint: Think repetition and isolation.

Quiz
Question: Which module is preferred for high-accuracy timing?

Type: mcq

Options: time, datetime, timeit

Correct Answer: timeit

Explanation: The timeit module is designed for accurate benchmarking of small code snippets.

Hint: It repeats execution for precision.

Question: True or False: timeit can be used to time entire Python scripts easily.

Type: boolean

Options: True, False

Correct Answer: False

Explanation: timeit is best for small snippets or functions, not entire scripts.

Hint: Think about its design purpose.

Challenge Problems
Problem: Write a function that uses a custom context manager to time the execution of any block passed into it.

Solution:

from contextlib import contextmanager
import time

@contextmanager
def timer():
start = time.time()
yield
end = time.time()
print(f"Elapsed time: {end - start}")

with timer():
[x**2 for x in range(100000)]
Hint: Use @contextmanager and yield in the right place.

Problem: Use timeit to compare the execution time of list comprehension vs generator expression.

Solution:

import timeit
list_time = timeit.timeit('[x for x in range(1000)]', number=10000)
gen_time = timeit.timeit('(x for x in range(1000))', number=10000)
print(f"List: {list_time}, Generator: {gen_time}")
Hint: Compare performance differences of memory usage.