-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_executor.py
More file actions
96 lines (76 loc) · 2.69 KB
/
code_executor.py
File metadata and controls
96 lines (76 loc) · 2.69 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
"""
代码执行器
安全执行和测试代码性能
"""
import time
import random
class CodeExecutor:
def __init__(self):
# 生成测试数据
self.test_data = [random.randint(1, 1000) for _ in range(1000)]
def measure_time(self, code, runs=5):
"""测量代码执行时间"""
try:
# 创建命名空间
namespace = {}
# 执行代码定义函数
exec(code, namespace)
# 检查函数是否存在
if 'sort_array' not in namespace:
print("❌ 函数 sort_array 未定义")
return None
sort_func = namespace['sort_array']
# 测试正确性
test_arr = [3, 1, 4, 1, 5, 9, 2, 6]
result = sort_func(test_arr.copy())
expected = sorted(test_arr)
if result != expected:
print(f"❌ 排序错误: {result} != {expected}")
return None
# 测量性能(多次运行取平均)
times = []
for _ in range(runs):
test_copy = self.test_data.copy()
start = time.perf_counter()
sort_func(test_copy)
end = time.perf_counter()
times.append(end - start)
avg_time = sum(times) / len(times)
return avg_time
except Exception as e:
print(f"❌ 执行错误: {e}")
return None
def test_correctness(self, code):
"""测试代码正确性"""
test_cases = [
[3, 1, 4, 1, 5, 9, 2, 6],
[1, 2, 3, 4, 5],
[5, 4, 3, 2, 1],
[1],
[],
[1, 1, 1, 1]
]
try:
namespace = {}
exec(code, namespace)
sort_func = namespace['sort_array']
for test in test_cases:
result = sort_func(test.copy())
expected = sorted(test)
if result != expected:
return False, f"Failed on {test}"
return True, "All tests passed"
except Exception as e:
return False, str(e)
if __name__ == "__main__":
# 测试
executor = CodeExecutor()
bubble_sort = """def sort_array(arr):
n = len(arr)
for i in range(n):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr"""
time_taken = executor.measure_time(bubble_sort)
print(f"冒泡排序耗时: {time_taken:.6f}s")