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.

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

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

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