0

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 :

  • I thought timer to calculate a code performance should be consistent? How to know that a syntax or a tactic performs better than the other? (run more efficiently than the other) Any thoughts on this?

Thanks before. Regards, Arief

  • The fluctuations in time seem small but you should use `timeit` module for this anyway – Chris_Rands Jun 08 '17 at 15:19
  • 2
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Chris_Rands Jun 08 '17 at 15:19
  • Regards @Chris_Rands what's the difference with `timeit` ? My key question is how to understand and choose better syntaxes or tactics for efficient code. Thanks –  Jun 08 '17 at 17:23

1 Answers1

0

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.

Alioth
  • 595
  • 4
  • 11