user7986928
user7986928

Reputation:

How to analyze a Python code's performance?

Regards. To analyze Python code's performance, may the code below does it?

import time

to = time.clock(); x = [];
for i in range(0,4):
    x.append(i*0.1);
tend = time.clock(); print(tend-to);

to = time.clock();
y = list(map(lambda x: x*0.1, list(range(0,4))));
tend = time.clock(); print(tend-to);

The timers show inconsistency. But sometimes, the result of the two timers also shows inconsistency (sometimes the first timer is faster, sometimes the second one is, although the first one tends to be faster). Some outputs :

4.631622925399206e-05
4.4898385501326854e-05

4.9624531343562917e-05
6.852911471254275e-05

5.0569760512011734e-05
4.867930217511418e-05

3.78091667379527e-05
2.5993802132341648e-05

My question pertain to the code above :

Thanks before. Regards, Arief

Upvotes: 1

Views: 552

Answers (2)

Jakob Bagterp
Jakob Bagterp

Reputation: 1324

Wouldn't it be more elegant to wrap the code in a function and use a function decorator such as @function_timer()? For example:

from timer import function_timer

@function_timer()
def my_function():
    x = [];
    for i in range(0,4):
        x.append(i * 0.1);

my_function()

The terminal output would be a little like this:

Elapsed time: 7.79 microseconds for thread MY_FUNCTION

PS: In full disclosure, I'm the author of Timer for Python, a lightweight package that makes it easy to measure time and performance of code.

Upvotes: 0

Alioth
Alioth

Reputation: 603

From the official documentation:

>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.3018611848820001
>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
0.2727368790656328
>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
0.23702679807320237

In other words: if we strive to talk about a precision in execution time measurements - we restricted to iterate a simple function several thousands times to elicit all side effects.

Upvotes: -1

Related Questions