如何多次运行一个函数

时间:2013-12-11 17:09:19

标签: python python-2.7 python-3.x

我必须在1000次运行中找到我的函数运行时间的平均值。我应该使用哪些代码使其运行1000次然后找到它们的平均值? 我的职责是:

import time

t0 = time.clock()

def binary_search(my_list, x):

    left=0
    right=len(my_list)-1
    while left<=right:
        mid = (left+right)//2
        if my_list[mid]==x:
            return True
        elif my_list[mid] < x: #go to right half
            left = mid+1
        else:              #go to left half
            right = mid-1
    return False  #if we got here the search failed
t1 = time.clock()

print("Running time: ", t1-t0, "sec")

5 个答案:

答案 0 :(得分:7)

您应该使用timeit模块:

>>> timeit.timeit('test()', setup='from __main__ import test')
0.86482962529626661

获得平均结果:

>>> timeit.timeit('test()', setup='from __main__ import test', number=1000)/1000
8.4928631724778825e-07

答案 1 :(得分:4)

如果只是少量代码,我建议使用timeit。您可以使用编号 kwarg选择重复该功能的次数。

答案 2 :(得分:3)

最好的方法是使用探查器BTW,如果你不想处理这种复杂性,这里有一些代码:

t0 = time.time()

for i in xrange(1000):
    binary_search([1]*1000000,2)

t1 = time.time()
avg = (t1 - t0)/1000

print( "Average Time Taken",avg )

输出:

('Average Time Taken', 0.007341000080108642)

答案 3 :(得分:1)

使用分析可能是您最好的选择。一切都已经为您编码,可以为您提供准确的报告。看看这个:

http://docs.python.org/2/library/profile.html

只需插入:

import cProfile
cProfile.run('foo()')

Blammo,报告完成了。此外,我个人不知道我是否会使用timeit。它适用于非常小的片段,我认为您将使用性能分析获得更准确的时间。找到答案的一种方法是实现BOTH以查看差异。告诉我们结果! :)

答案 4 :(得分:1)

我添加了test_speed()函数,如果你调用它会做你想要的。首先设置some_list和some_values或将其传递给test_speed()。

  import time

    def test_speed():
      results = []
      for _ in range(10000):
        t0 = time.clock()
        binary_search(some_list, some_value)
        t1 = time.clock()
        results.append(t1-t0)
      return sum(results) / len(results)

    def binary_search(my_list, x):

        left=0
        right=len(my_list)-1
        while left<=right:
            mid = (left+right)//2
            if my_list[mid]==x:
                return True
            elif my_list[mid] < x: #go to right half
                left = mid+1
            else:              #go to left half
                right = mid-1
        return False  #if we got here the search failed
相关问题