3

Possible Duplicate:
Python: Time a code segment for testing performance (with timeit)

In C++, you can time blocks of code fairly easily, see code below. Is there any way to do this python? (easily) Thanks!

time_t startTime = clock();

// Do stuff

time_t endTime = clock();

cout << "Difference in time(milliseconds) : " << endTime - startTime << endl;
1

4 Answers 4

15

Word-for-word translation of your code

import datetime
start = datetime.datetime.now()
// do stuff
finish = datetime.datetime.now()
print(finish-start)
Sign up to request clarification or add additional context in comments.

Comments

13

Try using the profilers available in the standard library.

Below is an example how to profile a script using cProfile from a command line. cProfile is one of the profilers available in all Python distributions.

$ python -m cProfile euler048.py

1007 function calls in 0.061 CPU seconds

Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.061    0.061 <string>:1(<module>)
 1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
    1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
    1    0.000    0.000    0.061    0.061 {execfile}
    1    0.002    0.002    0.053    0.053 {map}
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler objects}
    1    0.000    0.000    0.000    0.000 {range}
    1    0.003    0.003    0.003    0.003 {sum}

Comments

4

You may wish to checkout the timeit module, it is extremely handy for timing small snippets of code.

Typical example:

from timeit import Timer

def foo():
    # some code here

t1 = Timer("""foo()""", """from __main__ import foo""")
print t1.timeit(1000)  # runs foo() 1000 times and returns the time taken

Comments

1

I'd break the section you want to time into a function and put a timing decorator around it that times the code.

This saves on code duplication and has he added benefit that you can store/log the function name and args with the timing stats.

3 Comments

If you want this kind of control and statistics I'd strongly advise against doing that. It's like inventing the wheel again. Use a profiler instead! This is exactly what they do, without littering your source code. See this answer
I agree with fridge to some extent. Sometimes you want your code to log and monitor performance as it lives/runs in the real world a profiler isn't a good solution here.
That's true, good point.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.