2017-04-19 132 views
1

我正在嘗試使用timeit來創建一個程序,最終將打印出另一個程序的bigO。如果我嘗試使用lambda而不是字符串參數,程序就會掛起。如果我使用如下所示的字符串arg,我會得到發佈的錯誤。Python函數未定義

[email protected]:~$ 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) 

回答

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) 
+0

使用你的代碼,該程序不幸被凍結。 – DRoc101

+0

你能告訴我你作爲參數傳遞了什麼? – n33rma

+0

「python3 as10.py cs23_as10_constant」 這是我們運行的用於測試程序的命令。我們的服務器上有一系列默認程序用於此目的。 – DRoc101