views:

644

answers:

3

I'm new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation.

In java, I would write:

long timeBefore = System.currentTimeMillis();
doStuff();
long timeAfter = System.currentTimeMillis();
elapsed time = timeAfter - timeBefore;

I'm sure it's even easier in Python. Can anyone help?

A: 
python -m timeit -h
pixelbeat
+6  A: 

Equivalent in python would be:

>>> import time
>>> tic = time.clock()
>>> toc = time.clock()
>>> toc - tic

It's not clear what are you trying to do that for? Are you trying to find the best performing method? Then you should prob have a look at timeit.

SilentGhost
indeed, prob `clock` is better for this sort of measurements.
SilentGhost
Thanks for providing the equivalent. I'll have to look into `timeit` in the future, but for my current small exercise this will be sufficient.
FarmBoy
Note that `time.clock` doesn't do the same on all platforms. More notably, on unix it returns processor time, not clock time.
nosklo
+6  A: 

Use timeit. http://docs.python.org/library/timeit.html

Ramkumar Ramachandra