Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is not a robust observation

python3.2:

  >>> timeit.timeit("for i in range(100): s = '%s' % (i,)", number=100000)
  2.868873119354248
  >>> timeit.timeit("for i in range(100): s = '%s' % i", number=100000)
  2.615748882293701
  >>> timeit.timeit("for i in range(100): s = str(i)", number=100000)
  2.4016571044921875
  >>> timeit.timeit("for i in range(100): s = i.__str__()", number=100000)
  1.8993198871612549
python2.7:

  >>> timeit.timeit("for i in xrange(100): s = '%s' % (i,)", number=100000)
  1.9474480152130127
  >>> timeit.timeit("for i in xrange(100): s = '%s' % i", number=100000)
  1.6135330200195312
  >>> timeit.timeit("for i in xrange(100): s = str(i)", number=100000)
  2.009705066680908
  >>> timeit.timeit("for i in xrange(100): s = i.__str__()", number=100000)
  1.539802074432373


It would seem that loop bookkeeping dominates execution time here. Without it, I get quite different results:

    >>> timeit.timeit("'%s' % i", setup="i = 42", number=1000000)
    0.31799793243408203
    >>> timeit.timeit("str(i)", setup="i = 42", number=1000000)
    0.4146881103515625
This is another argument for profiling everything.


On the contrary, the time per inner iteration is slightly higher this way and the same conclusions hold:

1. python3.2 str() is at least as fast as '%s' formatting

2. '%s' is slightly faster than str() with python2.7

3. theint.__str__() is faster than either alternative in all cases


And also, for using timeit correctly. The command line usage is handy too: python -m timeit -s "i=42" "str(i)"




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: