简体   繁体   中英

how to run a function multiple times

I have to find the average of my function running time, out of 1000 runnings. which code should I use to make it run 1000 times and then find the average of them? my function is:

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

You should use the timeit module for this:

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

Getting the average result:

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

I would suggest using timeit if it's just a small amount of code. You can select the number of times to repeat the function using the number kwarg.

The best way is to use a profiler BTW if you don't want to deal with such complexity here's some code:

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 )

Output:

('Average Time Taken', 0.007341000080108642)

Using profiling is probably your best bet. Everything is already coded for you and can give you an accurate report of the matter. Check this out:

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

Just insert this:

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

Blammo, report done. Furthermore, I personally don't know if I would use timeit. It is meant for very small snippets, and I think you are going to get a more accurate timing using profiling. One way to find out though is to implement BOTH to see the differences. Tell us the results! :)

I have added test_speed() function that will do what you desire if you call it. Just first set some_list and some_values or pass it to the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM