0

Hi
i was wondering the best way to time how long a function/program takes
i cant work out how to do it. I tried fiddling with the time module yet i keep
doing the wrong things.

4
Contributors
3
Replies
5
Views
9 Years
Discussion Span
Last Post by woooee
0

Example using the timeit module:

def my_function():
    return results

if __name__ == '__main__':
    import timeit
    t = timeit.Timer("my_function()", "from __main__ import my_function")
    print t.timeit(1000)

Note that timeit() defaults to 1,000,000 iterations. If your function is somewhat slow, you may want to specify the number of iterations (1000 in the example above).

0

You can also use Python's module profile:

import profile

def get_primes3(n):
    if n < 2:  return []
    if n == 2: return [2]
    nums = range(3, n, 2)
    idx = 0
    while idx <= (n - 1)**0.5 - 2:
        for j in xrange( idx + nums[idx], n//2 - 1, nums[idx] ):
            # replace nonprime with zero (False)
            nums[j] = 0
        idx += 1
        while idx < n - 2:
            if nums[idx] != 0:
                break
            idx += 1
    # remove all zero items
    return [2] + [x for x in nums if x != 0]

profile.run('get_primes3(15000)')

"""
result of profile.run

         5 function calls in 0.004 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 :0(range)
        1    0.000    0.000    0.000    0.000 :0(setprofile)
        1    0.003    0.003    0.004    0.004 <module3>:3(get_primes3)
        1    0.000    0.000    0.004    0.004 <string>:1(?)
        1    0.000    0.000    0.004    0.004 profile:0(get_primes3(15000))
        0    0.000             0.000          profile:0(profiler)
"""
0

And if you mean something very simple to time some program once, use datetime.

import datetime
import time
start_time = datetime.datetime.now()
time.sleep(2)
print datetime.datetime.now() - start_time
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.