Skip to content

Tutorial: timer

Paul Alexander Bilokon edited this page Dec 15, 2024 · 1 revision

Timer Utilities Tutorial

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.


1. Overview

Functionality

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.

2. Timer Class

Description

The Timer class records the start and end times of a code block, providing the elapsed time in seconds.

Key Attributes

  • stopped: A boolean indicating whether the timer has stopped.
  • time: The elapsed time in seconds.

Usage

To use the Timer class, create a context using a with statement. The timer starts when entering the context and stops when exiting it.


3. Usage Example

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.")

Output

The block took 5.00 seconds.

4. Unit Test Example

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()

5. How It Works

Workflow

  1. When entering the context, the timer records the current time as the start time.
  2. When exiting the context, the timer records the end time and calculates the elapsed time.

Precision

The timer uses time.perf_counter() for high-resolution timing.


6. Conclusion

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.