我想在python中使用兩個不同的函數。在Python中計時函數
第一:
import cProfile
def bin_search(A, first,last, target):
#returns index of target in A, if present
#returns -1 if target is not present in A
if first > last:
return -1
else:
mid = (first+last)/2
if A[mid]==target:
return mid
elif A[mid]>target:
return bin_search(A,first,mid-1,target)
else:
return bin_search(A,mid+1,last,target)
第二
def trin_search(A,first,last,target):
#returns index of target in A, if present
#returns -1 if target is not present in A
if target> last or target<first:
return -1
if first>last:
return -1
else:
one_third=first+(last-first)/3
two_thirds=first+2*(last-first)/3
if A[one_third]==target:
return one_third
elif A[one_third]>target:
#search the left-hand third
return trin_search(A,first, one_third,target)
elif A[two_thirds]==target:
return two_thirds
elif A[two_thirds]>target:
#search the middle third
return trin_search(A,one_third+1,two_thirds-1,target)
else:
#search the right-hand third
return trin_search(A,two_thirds+1,last,target)
我試圖用cprofile.run()方法來計時他們。我呼籲:
cprofile.run('trin_search(newlist, newlist[0], newlist[-1], 17)')
和
cprofile.run('bin_search(newlist, newlist[0], newlist[-1], 17)')
與結果第一:
6 function calls (4 primitive calls) in 0.000 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :0(setprofile)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
3/1 0.000 0.000 0.000 0.000 Jan 18.py:16(trin_search)
0 0.000 0.000 profile:0(profiler)
1 0.000 0.000 0.000 0.000 profile:0(trin_search(newlist, newlist[0], newlist[-1], 17))
和第二
7 function calls (3 primitive calls) in 0.000 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
5/1 0.000 0.000 0.000 0.000 Jan 18.py:2(bin_search)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
這怎麼可能,他們採取0操作時間?
乾杯,
通常情況下,時間是最好的'timeit'完成。 – mgilson