3

Python で 2 つの異なる関数の時間を計ろうとしています。

最初:

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

そして2番目

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 である可能性はありますか?

乾杯、

4

2 に答える 2

3

他の使用法ですでに指摘されているtimeitように、パラメータを使用して関数の時間を計測する方法の例を次に示します。

import timeit

arg = 10

def foo(arg):
    return arg**arg

t=timeit.Timer("foo(arg)","from __main__ import foo, arg")
print t.timeit(5)

関数呼び出しで使用している関数と変数の両方をインポートする必要があることに注意してください。

また、「魔法のコマンド」がある場所でIPythonを使用することをお勧めします。そうすれば、簡単に実行できます。%timeit foo(arg)


あなたの例では、これはうまくいくはずです:

t=timeit.Timer("bin_search(newlist, newlist[0], newlist[-1], 17)",
                       "from __main__ import bin_search, newlist") 
于 2013-01-24T19:47:07.640 に答える
0

timeitモジュールを試してください。これは、コード スニペットのベンチマーク用に作成されています。

于 2013-01-24T19:11:18.320 に答える