-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_performance_analyzer.py
More file actions
215 lines (164 loc) · 6.73 KB
/
test_performance_analyzer.py
File metadata and controls
215 lines (164 loc) · 6.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""
Test script for the Performance Analyzer module.
This script tests the competitive analysis features including:
1. Theoretical operation estimation
2. Algorithm metadata retrieval
3. Live competitive benchmarking
Author: Algorithm Recommender Research Team
Version: 1.0.0
"""
import os
import sys
# Add package root to path
PACKAGE_ROOT = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, PACKAGE_ROOT)
from utils.performance_analyzer import (
PerformanceAnalyzer,
ALGORITHM_METADATA,
estimate_operations
)
from sorting.algorithms import SORTING_ALGORITHMS
from searching.array_search.algorithms import ARRAY_SEARCH_ALGORITHMS
def test_algorithm_metadata():
"""Test that algorithm metadata is complete."""
print("=" * 60)
print("TEST: Algorithm Metadata")
print("=" * 60)
required_fields = ['big_o_notation', 'complexity_class', 'best_case', 'worst_case']
for algo_name, metadata in ALGORITHM_METADATA.items():
print(f"\n{algo_name}:")
for field in required_fields:
value = metadata.get(field, 'MISSING')
print(f" {field}: {value}")
assert field in metadata, f"Missing {field} for {algo_name}"
print("\n✅ All algorithm metadata is complete!")
return True
def test_operation_estimation():
"""Test operation estimation for various algorithms."""
print("\n" + "=" * 60)
print("TEST: Operation Estimation")
print("=" * 60)
analyzer = PerformanceAnalyzer()
test_cases = [
('insertion_sort', 100),
('merge_sort', 100),
('quick_sort', 1000),
('binary_search', 1000),
('linear_search', 1000),
]
for algo, n in test_cases:
ops = analyzer.estimate_operations(algo, n=n)
metadata = analyzer.get_algorithm_metadata(algo)
print(f"\n{algo} (n={n}):")
print(f" Complexity: {metadata.get('big_o_notation', 'N/A')}")
print(f" Estimated operations: {ops:,}")
assert ops > 0, f"Operation count should be positive for {algo}"
print("\n✅ Operation estimation works correctly!")
return True
def test_competitive_benchmark_sorting():
"""Test competitive benchmarking for sorting algorithms."""
print("\n" + "=" * 60)
print("TEST: Competitive Benchmark (Sorting)")
print("=" * 60)
analyzer = PerformanceAnalyzer()
# Test with a small array
test_array = [5, 2, 8, 1, 9, 3, 7, 4, 6, 0]
valid_algos = list(SORTING_ALGORITHMS.keys())
analysis = analyzer.run_competitive_benchmark(
task_type='sorting',
selected_algo='quick_sort',
valid_algos=valid_algos,
input_data=test_array,
algorithm_funcs=SORTING_ALGORITHMS
)
print(f"\nSelected Algorithm: {analysis.selected_algorithm}")
print(f"Comparison Table ({len(analysis.comparison_table)} entries):")
for entry in analysis.comparison_table:
marker = "★" if entry['is_selected'] else " "
print(f" {marker} {entry['algorithm']}: {entry['est_ops']:,} ops - {entry['complexity']}")
if analysis.benchmark_results:
print(f"\nBenchmark Results ({len(analysis.benchmark_results)} entries):")
for result in analysis.benchmark_results:
marker = "★" if result['is_selected'] else " "
time_ms = result['execution_time_ns'] / 1_000_000
print(f" {marker} {result['algorithm']}: {time_ms:.4f} ms")
if analysis.relative_speedup:
print(f"\n{analysis.relative_speedup}")
print("\n✅ Competitive benchmarking works correctly!")
return True
def test_competitive_benchmark_search():
"""Test competitive benchmarking for search algorithms."""
print("\n" + "=" * 60)
print("TEST: Competitive Benchmark (Array Search)")
print("=" * 60)
analyzer = PerformanceAnalyzer()
# Test with a sorted array (so all search algos are valid)
test_array = list(range(0, 100, 10)) # [0, 10, 20, ..., 90]
target = 50
valid_algos = ['linear_search', 'binary_search', 'jump_search', 'exponential_search']
analysis = analyzer.run_competitive_benchmark(
task_type='array_search',
selected_algo='binary_search',
valid_algos=valid_algos,
input_data=test_array,
algorithm_funcs=ARRAY_SEARCH_ALGORITHMS,
target=target
)
print(f"\nSelected Algorithm: {analysis.selected_algorithm}")
print(f"Comparison Table ({len(analysis.comparison_table)} entries):")
for entry in analysis.comparison_table:
marker = "★" if entry['is_selected'] else " "
print(f" {marker} {entry['algorithm']}: {entry['est_ops']:,} ops - {entry['complexity']}")
if analysis.benchmark_results:
print(f"\nBenchmark Results ({len(analysis.benchmark_results)} entries):")
for result in analysis.benchmark_results:
marker = "★" if result['is_selected'] else " "
time_ns = result['execution_time_ns']
print(f" {marker} {result['algorithm']}: {time_ns:,} ns")
if analysis.relative_speedup:
print(f"\n{analysis.relative_speedup}")
print("\n✅ Search benchmarking works correctly!")
return True
def test_convenience_function():
"""Test the convenience estimate_operations function."""
print("\n" + "=" * 60)
print("TEST: Convenience Function")
print("=" * 60)
test_array = list(range(1000))
ops = estimate_operations('merge_sort', test_array)
print(f"estimate_operations('merge_sort', array_of_1000): {ops:,}")
assert ops > 0, "Should return positive operation count"
print("\n✅ Convenience function works correctly!")
return True
def main():
"""Run all tests."""
print("\n" + "=" * 60)
print("PERFORMANCE ANALYZER TEST SUITE")
print("=" * 60)
tests = [
("Algorithm Metadata", test_algorithm_metadata),
("Operation Estimation", test_operation_estimation),
("Competitive Benchmark (Sorting)", test_competitive_benchmark_sorting),
("Competitive Benchmark (Search)", test_competitive_benchmark_search),
("Convenience Function", test_convenience_function),
]
results = []
for name, test_func in tests:
try:
result = test_func()
results.append((name, result))
except Exception as e:
print(f"\n❌ {name} FAILED: {e}")
results.append((name, False))
print("\n" + "=" * 60)
print("TEST SUMMARY")
print("=" * 60)
for name, passed in results:
status = "✅ PASSED" if passed else "❌ FAILED"
print(f" {status}: {name}")
total_passed = sum(1 for _, passed in results if passed)
print(f"\n{total_passed}/{len(results)} tests passed")
return all(passed for _, passed in results)
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)