python-3.xperformance-testing

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


Solution

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