-
Notifications
You must be signed in to change notification settings - Fork 0
Tutorial: timer
This tutorial introduces the Timer
utility from the thalesians.adiutor.timer
module. The Timer
class is a context manager that simplifies measuring the execution time of code blocks.
The Timer
class allows you to:
- Measure the duration of a code block.
- Access timing information after the block completes.
- Ensure consistent handling of timing tasks using a context manager.
The Timer
class records the start and end times of a code block, providing the elapsed time in seconds.
- stopped: A boolean indicating whether the timer has stopped.
- time: The elapsed time in seconds.
To use the Timer
class, create a context using a with
statement. The timer starts when entering the context and stops when exiting it.
Below is an example of using the Timer
class to measure the duration of a code block:
import time
from thalesians.adiutor.timer import Timer
# Measure the execution time of a code block
with Timer() as t:
time.sleep(5) # Simulate a task that takes 5 seconds
print(f"The block took {t.time:.2f} seconds.")
The block took 5.00 seconds.
The following unit test ensures the Timer
class works as expected:
import time
import unittest
from thalesians.adiutor.timer import Timer
class TestTimer(unittest.TestCase):
def test_timer(self):
with Timer() as t:
time.sleep(5)
self.assertTrue(t.stopped)
self.assertGreater(t.time, 4.)
self.assertLess(t.time, 6.)
if __name__ == '__main__':
unittest.main()
- When entering the context, the timer records the current time as the start time.
- When exiting the context, the timer records the end time and calculates the elapsed time.
The timer uses time.perf_counter()
for high-resolution timing.
The Timer
class is a simple and efficient tool for measuring code execution time. It provides accurate timing information and ensures clean and reusable timing logic using Python's context manager.
Use this utility to profile code blocks and identify performance bottlenecks in your applications.