2014-01-21 65 views
0
import time 

def average(numbers): 
    "Return the average (arithmetic mean) of a sequence of numbers." 
    return sum(numbers)/float(len(numbers)) 

#example function 

def domath(a,b,c): 
    a+b+c 
    a*b*c 
    a/b/c 
    a-b-c 
    a^b 
    b^c 


def timedcalls(n, fn, *args): 
    times=[] 
    if type(n)==int: 
     t0 = time.clock() 
     for rep in range(n): 
      t0 = time.clock() 
      fn(*args) 
      t1 = time.clock() 
      times.append(t1-t0) 
    else: 
     start=time.clock() 
     while time.clock-start<int(n): 
      t0 = time.clock() 
      fn(*args) 
      t1 = time.clock() 
      times.append(t1-t0)  
    return min(times), average(times), max(times) 

print timedcalls(5.0, domath, 1,2,3) 

此代碼適用於int類型,但由於某種原因,如果我使用浮點數,它會給我這個錯誤。爲什麼我得到一個類型錯誤?

Traceback (most recent call last): 
    File "<stdin>", line 29, in <module> 
    File "<stdin>", line 22, in timedcalls 
TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'float' 

這一行:

return min(times), average(times), max(times) 
+1

請修復您的代碼格式 – inspectorG4dget

回答

7
while time.clock-start<int(n): 

應該

while time.clock()-start<int(n): 

你不是調用time.clock功能

注意在回溯它說它不能做減法之間'builtin_function_or_method' and 'float'

相關問題