4

From interpreter, I get:

>>> timeit.repeat("-".join( str(n) for n in range(10000) ) , repeat = 3, number=10000)
[1.2294530868530273, 1.2298660278320312, 1.2300069332122803] # this is seconds 

From commandline, I get:

$ python -m timeit -n 10000 '"-".join(str(n) for n in range(10000))'
10000 loops, best of 3: 1.79 msec per loop # this is milli second 

Why this difference in magnitude of timings in the two cases?

Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208
  • i remember python has problem for calculating float point data type.i suggest you use a module for do calculations. – PersianGulf Oct 16 '13 at 21:13

1 Answers1

8

The two lines aren't measuring the same thing. In the first snippet, you're timing the calculation 0-1-2-...-9999. while in the second snippet you're timing the string concatenation "-".join(str(n) for n in range(10000)).

In addition, timeit and repeat report the total time, while the CLI averages the time over the number of iterations. So the first code actually takes 12.29 ms "per loop".

  • I don't see it. Both times, the code that's executed is `"-".join( str(n) for n in range(10000))`, isn't it? It's executed a different number of times, but it's the same code? What am I overlooking? – Tim Pietzcker Oct 16 '13 at 20:44
  • 2
    @TimPietzcker In the first, `"-".join( str(n) for n in range(10000))` is evaluated and *its result* is passed to `timeit.repeat`. If there were additional quotes around said snippet, both would run the same code. –  Oct 16 '13 at 20:45
  • @delnam Can you elaborate please ? I don't get it ! – Ankur Agarwal Oct 16 '13 at 20:46
  • Ohhh...now I see it. Wow. Thanks. This is why I love StackOverflow so much. – Tim Pietzcker Oct 16 '13 at 20:48
  • @delnam So then why is the first case taking so much time. After all I am pretty much computing nothing in `repeat` in the first case. – Ankur Agarwal Oct 16 '13 at 20:49
  • @abc: You're computing 9999 integer subtractions. That isn't nothing. – Tim Pietzcker Oct 16 '13 at 20:50
  • @TimPietzcker That makes me feel better. – Ankur Agarwal Oct 16 '13 at 20:51
  • Though to be honest, I'd expect CPython to constant fold these substractions. And my 3.3 interpreter does in fact turn `1-2-...-999` into the constant `-499500`. The same up to `9999` results in a stack overflow in the parser. –  Oct 16 '13 at 20:53
  • @delnan @TimPietzcker Wait the result is just a string see `join` so there must be no subtractions happening. – Ankur Agarwal Oct 16 '13 at 20:55
  • 1
    @abc We're talking about the *first* code, the one which is only substractions. The string concatenation also happens in the first case, but once, outside `timeit`. –  Oct 16 '13 at 20:56
  • @delnam Got it! Yes the concatenated string when passed to `repeat` behaves like a command string. Thanks. – Ankur Agarwal Oct 16 '13 at 20:58