我正在尝试使用timeit创建一个程序,最终打印出另一个程序的bigO。如果我尝试使用lambda而不是字符串参数,程序就会挂起。如果我使用如下所示的字符串arg,我会收到发布的错误。
pdralston@jeff:~$ python3 as10.py cs23_as10_constant
Traceback (most recent call last):
File "as10.py", line 15, in <module>
elapsed_1 = timeit.timeit("func_run('1024')")
File "/usr/lib/python3.5/timeit.py", line 213, in timeit
return Timer(stmt, setup, timer, globals).timeit(number)
File "/usr/lib/python3.5/timeit.py", line 178, in timeit
timing = self.inner(it, self.timer)
File "<timeit-src>", line 6, in inner
NameError: name 'func_run' is not defined
不满意的代码
import sys
import subprocess
import timeit
command = sys.argv[1]#command line arg for executable to be tested
def func_run(parameter): #looks pretty defined to me...
subprocess.run([command, parameter])#runs the executable with an arg for data sample size
answers = { #will use this for output eventually
0: "O(1)",
1: "O(log n)",
2: "O(n)",
3: "O(n log n)",
4: "O(n^2)",
5: "O(n^3)"}
elapsed_1 = timeit.timeit("func_run('1024')")#also tried lambda: func_run("1024") instead of a string
elapsed_2 = timeit.timeit("func_run('4096')")
elapsed_growth = elapsed_2 / elapsed_1
print(elapsed_growth)
答案 0 :(得分:2)
你需要包装你的功能。
import sys
import subprocess
import timeit
command = sys.argv[1]
def wrapper(func, *args, **kwargs):
def wrapped():
return func(*args, **kwargs)
return wrapped
def func_run(parameter):
subprocess.run([command, parameter])
yourArgs_1 = '1024'
yourArgs_2 = '4096'
wrapped_1 = wrapper(func_run, yourArgs_1)
wrapped_2 = wrapper(func_run, yourArgs_2)
answers = {
0: "O(1)",
1: "O(log n)",
2: "O(n)",
3: "O(n log n)",
4: "O(n^2)",
5: "O(n^3)"}
elapsed_1 = timeit.timeit(wrapped_1)
elapsed_2 = timeit.timeit(wrapped_2)
# Provide number of execution with number argument in timit function
# timeit.timeit(wrapped_1, number=10)
elapsed_growth = elapsed_2 / elapsed_1
print(elapsed_growth)