Performance Tools
This example demonstrates time-based performance tools in the True-Core time module.
Example Code
Performance Tools Example
1"""
2Examples of using time-related performance tools and decorators.
3"""
4
5import time
6
7from true.time import timeout, timer, Time
8
9
10@timeout(2.0)
11def long_running_task():
12 """A task that takes too long and should timeout."""
13 time.sleep(3)
14 return "This should never be returned"
15
16
17@timeout(5.0)
18def quick_task():
19 """A task that completes within the timeout."""
20 time.sleep(1)
21 return "Task completed successfully"
22
23
24@timer
25def cpu_intensive_task():
26 """A CPU-intensive task to demonstrate the timer decorator."""
27 result = 0
28 for i in range(1000000):
29 result += i
30 return result
31
32
33def demo_timeout_decorator():
34 """Demonstrate the timeout decorator."""
35 print("=== Timeout Decorator ===")
36
37 print("Running quick task...")
38 try:
39 result = quick_task()
40 print(f"Quick task result: {result}")
41 except TimeoutError as e:
42 print(f"Quick task error: {e}")
43
44 print("\nRunning long task...")
45 try:
46 result = long_running_task()
47 print(f"Long task result: {result}")
48 except TimeoutError as e:
49 print(f"Long task error: {e}")
50
51
52def demo_timer_decorator():
53 """Demonstrate the timer decorator."""
54 print("\n=== Timer Decorator ===")
55
56 print("Running CPU intensive task...")
57 result = cpu_intensive_task()
58 print(f"Task result: {result}")
59
60
61def demo_timer_context():
62 """Demonstrate the timer context manager."""
63 print("\n=== Timer Context Manager ===")
64
65 time_obj = Time.now()
66
67 print("Measuring block execution time...")
68 with time_obj.timer():
69 # Simulate some work
70 time.sleep(1.5)
71 result = sum(range(100000))
72
73 print(f"Computed result: {result}")
74
75
76def demo_performance_comparison():
77 """Demonstrate comparing performance of different approaches."""
78 print("\n=== Performance Comparison ===")
79
80 @timer
81 def method1():
82 return sum(i * i for i in range(1000000))
83
84 @timer
85 def method2():
86 return sum([i * i for i in range(1000000)])
87
88 print("Method 1 (generator):")
89 result1 = method1()
90
91 print("\nMethod 2 (list comprehension):")
92 result2 = method2()
93
94 print(f"\nResults match: {result1 == result2}")
95
96
97if __name__ == "__main__":
98 demo_timeout_decorator()
99 demo_timer_decorator()
100 demo_timer_context()
101 demo_performance_comparison()
Key Features
Performance Measurement - Code timing - Profiling support - Benchmark tools
Statistics - Timing statistics - Performance analysis - Data visualization
Advanced Features - Custom metrics - Reporting tools - Integration support