Skip to content

Instantly share code, notes, and snippets.

@teepark
Created June 1, 2011 19:34
Show Gist options
  • Save teepark/1003105 to your computer and use it in GitHub Desktop.
Save teepark/1003105 to your computer and use it in GitHub Desktop.
what's so fast about namedtuple?
$ python -m timeit -s "import collections; Point = collections.namedtuple('Point', ('x', 'y'));" "Point(5, 11)"
1000000 loops, best of 3: 0.739 usec per loop
$ python -m timeit "(5, 11)"
10000000 loops, best of 3: 0.0267 usec per loop
$ python -m timeit -s "import collections; p = collections.namedtuple('Point', ('x', 'y'))(5, 11)" "x, y = p"
10000000 loops, best of 3: 0.134 usec per loop
$ python -m timeit -s "p = (5, 11)" "x, y = p"
10000000 loops, best of 3: 0.0678 usec per loop
$ python -m timeit -s "import collections; p = collections.namedtuple('Point', ('x', 'y'))(5, 11)" "p.x"
10000000 loops, best of 3: 0.15 usec per loop
$ python -m timeit -s "import collections; p = collections.namedtuple('Point', ('x', 'y'))(5, 11)" "p[0]"
10000000 loops, best of 3: 0.0531 usec per loop
$ python -m timeit -s "p = (5, 11)" "p[0]"
10000000 loops, best of 3: 0.0529 usec per loop
$ python -m timeit -s "obj = type('Point', (), {}); obj.x = 5" "obj.x"
10000000 loops, best of 3: 0.0507 usec per loop
$ python --version
Python 2.6.5
$ uname -a
Linux piggy 2.6.32-31-generic #61-Ubuntu SMP Fri Apr 8 18:25:51 UTC 2011 x86_64 GNU/Linux
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment