[Tutor] Help execution time calculation:

Steven D'Aprano steve at pearwood.info
Wed Jul 14 17:23:26 CEST 2010


On Thu, 15 Jul 2010 01:11:58 am Vineeth Rakesh wrote:
> Hello all,
>
> I want to calculate the execution time of a program. Say I have a
> function like below:
>
> def RepAdd(i):
>   j = 0
>   while(j<i):
>      j += 1
>   return j
>
> now I want to calculate the execution time of the function RepAdd
> when say 10 is passed as an argument. I did come across the module
> timeit, if that is the module to be used can any one illustrate it
> using the above program as input.

timeit is the *right* solution for timing small code snippets like 
RepAdd above, but the recipe for using it can appear a little 
mysterious.

If you have RepAdd in a file "test.py", then from the command line:

python -m timeit -s "from test import RepAdd" "RepAdd(10)"

should work.

Otherwise, type RepAdd into the Python interactive interpreter, or into 
IDLE, and then do this:

from timeit import Timer
t = Timer('RepAdd(10)', 'from __main__ import RepAdd')
print(min(t.repeat()))



-- 
Steven D'Aprano


More information about the Tutor mailing list