Skip to content

Instantly share code, notes, and snippets.

@mattrobenolt
Created December 15, 2012 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattrobenolt/4299723 to your computer and use it in GitHub Desktop.
Save mattrobenolt/4299723 to your computer and use it in GitHub Desktop.
Python benchmark ways to cast an integer to a string: `a` vs str(a) vs format vs % vs repr(a)
# Python 2.7.3
$ python -m timeit -s 'a=5' 'str(a)'
10000000 loops, best of 3: 0.177 usec per loop
$ python -m timeit -s 'a=5' '`a`'
10000000 loops, best of 3: 0.0571 usec per loop # Fastest, but seems like it's not good practice
$ python -m timeit -s 'a=5' '"%s".format(a)'
1000000 loops, best of 3: 0.236 usec per loop # Slowest
$ python -m timeit -s 'a=5' '"%s" % a'
10000000 loops, best of 3: 0.159 usec per loop
$ python -m timeit -s 'a=5' 'repr(a)'
10000000 loops, best of 3: 0.082 usec per loop # Fastest without bad practive
# Python 3.3.0
$ python3 -m timeit -s 'a=5' 'str(a)'
1000000 loops, best of 3: 0.355 usec per loop # Slowest
$ python3 -m timeit -s 'a=5' '"%s".format(a)'
1000000 loops, best of 3: 0.271 usec per loop
$ python3 -m timeit -s 'a=5' '"%s" % a'
10000000 loops, best of 3: 0.149 usec per loop # Fastest (tied)
$ python3 -m timeit -s 'a=5' 'repr(a)'
10000000 loops, best of 3: 0.157 usec per loop # Fastest (tied)
# PyPy [PyPy 1.9.0 with GCC 4.2.1]
$ pypy -m timeit -s 'a=5' 'str(a)'
100000000 loops, best of 3: 0.00236 usec per loop # Fastest (tied)
$ pypy -m timeit -s 'a=5' '`a`'
1000000000 loops, best of 3: 0.00168 usec per loop # Fastest with bad practice
$ pypy -m timeit -s 'a=5' '"%s".format(a)'
10000000 loops, best of 3: 0.0953 usec per loop # Slowest
$ pypy -m timeit -s 'a=5' '"%s" % a'
10000000 loops, best of 3: 0.0285 usec per loop
$ pypy -m timeit -s 'a=5' 'repr(a)'
100000000 loops, best of 3: 0.00201 usec per loop # Fastest (tied)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment