Repository navigation
Expand file tree
/
Copy pathbench.py
More file actions
354 lines (281 loc) · 10.5 KB
/
Copy pathbench.py
File metadata and controls
354 lines (281 loc) · 10.5 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#!/usr/bin/env python3
"""
DevFlow - Performance Benchmark Tool
生成和运行性能基准测试
Usage:
python bench.py --file algo.py
python bench.py --file algo.py --function sort_array
python bench.py --file algo.py --generate
python bench.py --dir src/ --run-all
"""
import argparse
import ast
import json
import os
import re
import sys
import time
from pathlib import Path
from typing import Dict, List, Optional, Tuple
def analyze_function(content: str, function_name: str) -> Optional[Dict]:
"""分析函数结构"""
try:
tree = ast.parse(content)
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) and node.name == function_name:
return {
"name": node.name,
"args": [arg.arg for arg in node.args.args],
"line": node.lineno,
"end_line": getattr(node, "end_lineno", node.lineno),
"decorators": [d.id if hasattr(d, "id") else str(d) for d in node.decorator_list]
}
except SyntaxError:
pass
return None
def extract_function_code(content: str, function_name: str) -> Optional[str]:
"""提取函数代码"""
lines = content.split("\n")
func_info = analyze_function(content, function_name)
if func_info:
start = func_info["line"] - 1
end = func_info["end_line"]
return "\n".join(lines[start:end])
return None
def list_functions(content: str) -> List[Dict]:
"""列出所有函数"""
functions = []
try:
tree = ast.parse(content)
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
functions.append({
"name": node.name,
"args": [arg.arg for arg in node.args.args],
"line": node.lineno
})
except SyntaxError:
pass
return functions
def generate_benchmark_template(function_name: str, func_info: Dict) -> str:
"""生成基准测试模板"""
args = func_info.get("args", [])
# 生成测试数据
test_data = []
for arg in args:
if arg in ("arr", "nums", "numbers", "list"):
test_data.append(f" {arg} = list(range(10000))")
elif arg in ("n", "count", "size"):
test_data.append(f" {arg} = 10000")
elif arg in ("s", "text", "string", "str"):
test_data.append(f" {arg} = 'test string ' * 1000")
elif arg in ("d", "dict", "data"):
test_data.append(" " + arg + " = {'key': 'value'} * 1000")
else:
test_data.append(f" {arg} = None # TODO: Add test data")
template = f'''#!/usr/bin/env python3
"""
Benchmark test for {function_name}
Generated by DevFlow
"""
import time
import statistics
from pathlib import Path
# Import the function
import sys
sys.path.insert(0, str(Path(__file__).parent))
from {Path(__file__).stem} import {function_name}
def benchmark_{function_name}(iterations=100):
"""Run benchmark for {function_name}"""
# Test data
{chr(10).join(test_data)}
# Warmup
print(f"Warming up {function_name}...")
for _ in range(10):
{function_name}({', '.join(args)})
# Benchmark
print(f"Running benchmark ({iterations} iterations)...")
times = []
for i in range(iterations):
start = time.perf_counter()
{function_name}({', '.join(args)})
end = time.perf_counter()
times.append(end - start)
if (i + 1) % 10 == 0:
print(f" Iteration {{i+1}}/{{iterations}}")
# Results
avg_time = statistics.mean(times)
min_time = min(times)
max_time = max(times)
std_dev = statistics.stdev(times) if len(times) > 1 else 0
print("\\n" + "=" * 60)
print(f"Benchmark Results: {function_name}")
print("=" * 60)
print(f"Iterations: {{iterations}}")
print(f"Avg Time: {{avg_time*1000:.3f}} ms")
print(f"Min Time: {{min_time*1000:.3f}} ms")
print(f"Max Time: {{max_time*1000:.3f}} ms")
print(f"Std Dev: {{std_dev*1000:.3f}} ms")
print(f"Throughput: {{1/avg_time:.0f}} ops/sec")
print("=" * 60)
return {{
"function": "{function_name}",
"iterations": iterations,
"avg_ms": avg_time * 1000,
"min_ms": min_time * 1000,
"max_ms": max_time * 1000,
"std_dev_ms": std_dev * 1000,
"ops_per_sec": 1 / avg_time
}}
if __name__ == "__main__":
result = benchmark_{function_name}()
# Save results
import json
with open("{function_name}_benchmark.json", "w") as f:
json.dump(result, f, indent=2)
print(f"\\nResults saved to {function_name}_benchmark.json")
'''
return template
def run_benchmark(benchmark_file: str) -> Optional[Dict]:
"""运行基准测试"""
try:
import subprocess
result = subprocess.run(
[sys.executable, benchmark_file],
capture_output=True,
text=True,
timeout=60
)
if result.returncode == 0:
# 尝试解析输出中的 JSON
output = result.stdout
print(output)
# 查找结果文件
json_files = list(Path(".").glob("*_benchmark.json"))
if json_files:
latest = max(json_files, key=lambda f: f.stat().st_mtime)
return json.loads(latest.read_text())
else:
print(f"Error: {result.stderr}", file=sys.stderr)
except Exception as e:
print(f"Error running benchmark: {e}", file=sys.stderr)
return None
def compare_results(result1: Dict, result2: Dict) -> Dict:
"""比较两个基准测试结果"""
comparison = {
"function": result1.get("function"),
"baseline": {
"avg_ms": result1.get("avg_ms"),
"ops_per_sec": result1.get("ops_per_sec")
},
"current": {
"avg_ms": result2.get("avg_ms"),
"ops_per_sec": result2.get("ops_per_sec")
},
"improvement": {}
}
if result1.get("avg_ms") and result2.get("avg_ms"):
speedup = result1["avg_ms"] / result2["avg_ms"]
comparison["improvement"]["speedup"] = f"{speedup:.2f}x"
comparison["improvement"]["faster"] = speedup > 1
return comparison
def format_report(results: List[Dict], format: str = "text") -> str:
"""格式化报告"""
if format == "json":
return json.dumps(results, indent=2, ensure_ascii=False)
lines = []
lines.append("=" * 60)
lines.append("DevFlow Performance Benchmark Report")
lines.append("=" * 60)
lines.append("")
for result in results:
lines.append(f"[{result.get('function', 'Unknown')}]")
lines.append(f" Iterations: {result.get('iterations', 'N/A')}")
lines.append(f" Avg Time: {result.get('avg_ms', 0):.3f} ms")
lines.append(f" Min Time: {result.get('min_ms', 0):.3f} ms")
lines.append(f" Max Time: {result.get('max_ms', 0):.3f} ms")
lines.append(f" Throughput: {result.get('ops_per_sec', 0):.0f} ops/sec")
lines.append("")
if not results:
lines.append("No benchmark results.")
lines.append("=" * 60)
return "\n".join(lines)
def main():
parser = argparse.ArgumentParser(
description="DevFlow Performance Benchmark Tool",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Generate benchmark for function
python bench.py --file algo.py --function sort_array --generate
# Run benchmark
python bench.py --file algo.py --function sort_array --run
# List functions
python bench.py --file algo.py --list
# Run all benchmarks in directory
python bench.py --dir src/ --run-all
"""
)
parser.add_argument("--file", "-f", help="Source file")
parser.add_argument("--dir", "-d", help="Directory to scan")
parser.add_argument("--function", "-fn", help="Function name")
parser.add_argument("--list", action="store_true", help="List functions")
parser.add_argument("--generate", action="store_true", help="Generate benchmark")
parser.add_argument("--run", action="store_true", help="Run benchmark")
parser.add_argument("--run-all", action="store_true", help="Run all benchmarks")
parser.add_argument("--iterations", "-i", type=int, default=100, help="Number of iterations")
parser.add_argument("--format", choices=["text", "json"], default="text", help="Output format")
parser.add_argument("--output", "-o", help="Output file path")
args = parser.parse_args()
# 列出函数
if args.list:
if not args.file:
print("Error: --file is required for --list", file=sys.stderr)
sys.exit(1)
content = Path(args.file).read_text(encoding="utf-8")
functions = list_functions(content)
print(f"Functions in {args.file}:")
for func in functions:
print(f" - {func['name']}({', '.join(func['args'])}) at line {func['line']}")
return
# 生成基准测试
if args.generate:
if not args.file or not args.function:
print("Error: --file and --function are required for --generate", file=sys.stderr)
sys.exit(1)
content = Path(args.file).read_text(encoding="utf-8")
func_info = analyze_function(content, args.function)
if not func_info:
print(f"Error: Function '{args.function}' not found", file=sys.stderr)
sys.exit(1)
template = generate_benchmark_template(args.function, func_info)
output_file = f"bench_{args.function}.py"
Path(output_file).write_text(template, encoding="utf-8")
print(f"Benchmark generated: {output_file}")
return
# 运行基准测试
if args.run:
if not args.file:
print("Error: --file is required for --run", file=sys.stderr)
sys.exit(1)
result = run_benchmark(args.file)
if result:
print(format_report([result], args.format))
return
# 运行所有基准测试
if args.run_all:
if not args.dir:
print("Error: --dir is required for --run-all", file=sys.stderr)
sys.exit(1)
results = []
for bench_file in Path(args.dir).glob("bench_*.py"):
print(f"\nRunning {bench_file}...")
result = run_benchmark(str(bench_file))
if result:
results.append(result)
print(format_report(results, args.format))
return
# 默认显示帮助
parser.print_help()
if __name__ == "__main__":
main()