Skip to content

Optimize namedtuple creation #72824

Closed
Closed

Description

@methane
BPO 28638
Nosy @gvanrossum, @rhettinger, @ncoghlan, @pitrou, @vstinner, @ericvsmith, @giampaolo, @methane, @serhiy-storchaka, @MojoVampire, @llllllllll, @zhangyangyu, @JelleZijlstra, @lazka, @ethanhs
PRs
  • bpo-28638: speed up namedtuple creation by avoiding exec #2736
  • bpo-28638: Optimize namedtuple() creation time by minimizing use of exec() #3454
  • Files
  • 28638-functools-no-namedtuple.patch
  • namedtuple-no-compile.patch
  • namedtuple1.py
  • namedtuple-clinic.diff
  • namedtuple-clinic2.diff
  • functools-CacheInfo-Makefile.patch
  • namedtuple-clinic3.patch
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = 'https://github.com/rhettinger'
    closed_at = <Date 2017-09-10.17:25:13.282>
    created_at = <Date 2016-11-08.04:07:24.207>
    labels = ['3.7', 'library', 'performance']
    title = 'Optimize namedtuple creation'
    updated_at = <Date 2017-09-10.17:25:13.282>
    user = 'https://github.com/methane'

    bugs.python.org fields:

    activity = <Date 2017-09-10.17:25:13.282>
    actor = 'rhettinger'
    assignee = 'rhettinger'
    closed = True
    closed_date = <Date 2017-09-10.17:25:13.282>
    closer = 'rhettinger'
    components = ['Library (Lib)']
    creation = <Date 2016-11-08.04:07:24.207>
    creator = 'methane'
    dependencies = []
    files = ['45386', '45388', '45399', '45578', '45580', '45724', '45738']
    hgrepos = []
    issue_num = 28638
    keywords = ['patch']
    message_count = 62.0
    messages = ['280277', '280279', '280282', '280283', '280284', '280285', '280288', '280291', '280297', '280298', '280300', '280303', '280356', '280543', '280560', '280561', '281336', '281339', '281356', '282172', '282178', '282182', '282278', '282279', '282412', '285615', '298400', '298444', '298453', '298457', '298482', '298485', '298486', '298487', '298488', '298489', '298490', '298491', '298493', '298499', '298500', '298503', '298514', '298515', '298566', '298570', '298571', '298574', '298581', '298601', '298630', '298631', '298637', '298641', '298648', '298653', '298670', '298681', '298730', '301700', '301804', '301819']
    nosy_count = 15.0
    nosy_names = ['gvanrossum', 'rhettinger', 'ncoghlan', 'pitrou', 'vstinner', 'eric.smith', 'giampaolo.rodola', 'methane', 'serhiy.storchaka', 'josh.r', 'llllllllll', 'xiang.zhang', 'JelleZijlstra', 'lazka', 'ethan smith']
    pr_nums = ['2736', '3454']
    priority = 'normal'
    resolution = 'fixed'
    stage = 'resolved'
    status = 'closed'
    superseder = None
    type = 'performance'
    url = 'https://bugs.python.org/issue28638'
    versions = ['Python 3.7']

    Activity

    1. methane commented on Nov 8, 2016

      @methane
      MemberAuthor

      I surprised how functools make import time slower.
      And I find namedtuple makes it slower.

      When I replaced

      _CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"])

      this line with _CachedInfo._source:

      (before)
      $ ~/local/py37/bin/python3 -m perf timeit -s 'import importlib, functools' -- 'importlib.reload(functools)'
      .....................
      Median +- std dev: 1.21 ms +- 0.01 ms

      (replaced)
      $ ~/local/py37/bin/python3 -m perf timeit -s 'import importlib, functools' -- 'importlib.reload(functools)'
      .....................
      Median +- std dev: 615 us +- 12 us

    2. added
      performance
      3.7 (EOL)
      stdlib
      on Nov 8, 2016
    3. changed the title [-]Creating namedtuple is too slow[/-] [+]Creating namedtuple is too slow to be used in common stdlib (e.g. functools)[/+] on Nov 8, 2016
    4. methane commented on Nov 8, 2016

      @methane
      MemberAuthor

      I feel this patch is safe enough to be landed in 3.6.

    5. zhangyangyu commented on Nov 8, 2016

      @zhangyangyu
      Member

      I doubt this deserves a change. The slow import is the case only the first time functools is imported. Later imports will just use the cache (sys.modules). And if this is gonna change, maybe we don't have to copy the entire namedtuple structure?

    6. methane commented on Nov 8, 2016

      @methane
      MemberAuthor

      The slow import is the case only the first time functools is imported. Later imports will just use the cache (sys.modules).

      Yes. But first import time is also important for CLI applications.
      That's why mercurial and Bazaar has lazy import system.

      Since many stdlib uses functools, many applications may be suffered from
      slow functools import even if we remove it from site.py.

      maybe we don't have to copy the entire namedtuple structure?

      https://docs.python.org/3.5/library/functools.html#functools.lru_cache

      The doc says it's a namedtuple. So it should be namedtuple compatible.

    7. zhangyangyu commented on Nov 8, 2016

      @zhangyangyu
      Member

      Yes. But first import time is also important for CLI applications.
      That's why mercurial and Bazaar has lazy import system.

      The lazy import system could benefit many libs so the result could be impressive. But here only functools is enhanced, half a millisecond is reduced.

      Performance of course is important, but replicating code sounds not good. It means you have to maintain two pieces.

    8. methane commented on Nov 8, 2016

      @methane
      MemberAuthor

      The lazy import system could benefit many libs so the result could be impressive. But here only functools is enhanced, half a millisecond is reduced.

      On the other hand, implementing lazy import makes application complex.

      This patch only enhance functools, but it is very important one module.
      Even if we remove functools from site.py, most applications relies on it,
      especially for functools.wraps().
      This patch can optimize startup time of them.

      Half milliseconds is small, but it isn't negligible on some situation.
      Some people loves tools quickly starts. For example, there are many
      people maintain their vimrc to keep <50~100ms startup time.
      And Python is common language to implement vim plugins.

      Additionally, it make noise when profiling startup time.
      I've very confused when I saw PyParse_AddToken() in profile.
      Less noise make it easy to optimize startup time.

      Performance of course is important, but replicating code sounds not good. It means you have to maintain two pieces.

      Yes. Balance is important.
      I want to hear more opinions from more other devs.

    9. serhiy-storchaka commented on Nov 8, 2016

      @serhiy-storchaka
      Member

      What is the main culprit, importing the collections module or compiling a named tuple?

    10. serhiy-storchaka commented on Nov 8, 2016

      @serhiy-storchaka
      Member

      Using namedtuple is not new in 3.6, thus this is not a regression that can be fixed at beta stage.

      Inlining the source of a named tuple class looks ugly solution. It would be better to write the source in separate file and import it. Makefile can have a rule for recreating this source file if collections.py is changed.

      More general solution would be to make namedtuple() using cached precompiled class and update the cache if it doesn't match namedtuple arguments.

      Yet one solution is to make namedtuple() not using compiling, but return patched local class. But Raymond is against this.

    11. methane commented on Nov 8, 2016

      @methane
      MemberAuthor

      What is the main culprit, importing the collections module or compiling a named tuple?

      In this time, later.
      But collections module takes 1+ ms to import too.
      I'll try to optimize it.

      Using namedtuple is not new in 3.6, thus this is not a regression that can be fixed at beta stage.

      Make sense.

      More general solution would be to make namedtuple() using cached precompiled class and update the cache if it doesn't match namedtuple arguments.

      What "precompiled class" means? pyc file? or source string to be
      executed?

      Yet one solution is to make namedtuple() not using compiling, but return patched local class. But Raymond is against this.

      I'll search the discussion.
      I think anther solution is reimplement namedtuple by C.
      As far as I remember, attrs [1] does it.

      [1] https://pypi.python.org/pypi/attrs

    12. serhiy-storchaka commented on Nov 8, 2016

      @serhiy-storchaka
      Member

      Here is a sample patch that make namedtuple() not using dynamic compilation. It has rough the same performance effect as inlining the named tuple source, but affects all named tuples.

    13. 50 remaining items

    14. giampaolo commented on Jul 18, 2017

      @giampaolo
      Contributor

      Should we consider a C-based implementation like https://github.com/llllllllll/cnamedtuple?
      It could improve speed even more, but would be harder to maintain and
      test and harder to keep compatible. My sense is that it's not worth
      it unless benchmarks show a really dramatic difference.

      I've just filed a ticket for this: llllllllll/cnamedtuple#7

    15. llllllllll commented on Jul 19, 2017

      llllllllllmannequin
      Mannequin

      I added a benchmark suite (using Victor's perf utility) to cnamedtuple. The results are here: https://github.com/llllllllll/cnamedtuple#benchmarks

      To summarize: type creation is much faster; instance creation and named attribute access are a bit faster.

    16. JelleZijlstra commented on Jul 19, 2017

      @JelleZijlstra
      Member

      I benchmarked some common namedtuple operations with the following script:

      #!/bin/bash
      echo 'namedtuple creation'
      ./python -m timeit -s 'from collections import namedtuple' 'x = namedtuple("x", ["a", "b", "c"])'

      echo 'namedtuple instantiation'
      ./python -m timeit -s 'from collections import namedtuple; x = namedtuple("x", ["a", "b", "c"])' 'x(1, 2, 3)'

      echo 'namedtuple attribute access'
      ./python -m timeit -s 'from collections import namedtuple; x = namedtuple("x", ["a", "b", "c"]); i = x(1, 2, 3)' 'i.a'

      echo 'namedtuple _make'
      ./python -m timeit -s 'from collections import namedtuple; x = namedtuple("x", ["a", "b", "c"])' 'x._make((1, 2, 3))'

      --------------------------------------
      With my patch as it stands now I get:

      $ ./ntbenchmark.sh 
      namedtuple creation
      2000 loops, best of 5: 101 usec per loop
      namedtuple instantiation
      500000 loops, best of 5: 477 nsec per loop
      namedtuple attribute access
      5000000 loops, best of 5: 59.9 nsec per loop
      namedtuple _make
      500000 loops, best of 5: 430 nsec per loop

      With unpatched CPython master I get:

      $ ./ntbenchmark.sh 
      namedtuple creation
      500 loops, best of 5: 409 usec per loop
      namedtuple instantiation
      500000 loops, best of 5: 476 nsec per loop
      namedtuple attribute access
      5000000 loops, best of 5: 60 nsec per loop
      namedtuple _make
      1000000 loops, best of 5: 389 nsec per loop

      So creating a class is about 4x faster (similar to the benchmarks various other people have run) and calling _make() is 10% slower. That's probably because of the line "if len(result) != cls._num_fields:" in my implementation, which would have been something like "if len(result) != 3" in the exec-based implementation.

      I also cProfiled class creation with my patch. These are results for creating 10000 3-element namedtuple classes:

           390005 function calls in 2.793 seconds
      

      Ordered by: cumulative time

      ncalls tottime percall cumtime percall filename:lineno(function)
      10000 0.053 0.000 2.826 0.000 <ipython-input-5-c37fa4922f0a>:1(make_nt)
      10000 1.099 0.000 2.773 0.000 /home/jelle/qython/cpython/Lib/collections/init.py:380(namedtuple)
      10000 0.948 0.000 0.981 0.000 {built-in method builtins.exec}
      100000 0.316 0.000 0.316 0.000 {method 'format' of 'str' objects}
      10000 0.069 0.000 0.220 0.000 {method 'join' of 'str' objects}
      40000 0.071 0.000 0.152 0.000 /home/jelle/qython/cpython/Lib/collections/init.py:439(<genexpr>)
      10000 0.044 0.000 0.044 0.000 {built-in method builtins.repr}
      30000 0.033 0.000 0.033 0.000 {method 'startswith' of 'str' objects}
      40000 0.031 0.000 0.031 0.000 {method 'isidentifier' of 'str' objects}
      40000 0.025 0.000 0.025 0.000 {method '__contains__' of 'frozenset' objects}
      10000 0.022 0.000 0.022 0.000 {method 'replace' of 'str' objects}
      10000 0.022 0.000 0.022 0.000 {built-in method sys._getframe}
      30000 0.020 0.000 0.020 0.000 {method 'add' of 'set' objects}
      20000 0.018 0.000 0.018 0.000 {built-in method builtins.len}
      10000 0.013 0.000 0.013 0.000 {built-in method builtins.isinstance}
      10000 0.009 0.000 0.009 0.000 {method 'get' of 'dict' objects}

      So about 35% of time is still spent in the exec() call to create __new__. Another 10% is in .format() calls, so using f-strings instead of .format() might also be worth it.

    17. JelleZijlstra commented on Jul 19, 2017

      @JelleZijlstra
      Member

      Thanks Joe! I adapted your benchmark suite to also run my implementation. See JelleZijlstra/cnamedtuple@61b6fbf for the code and results. The results are consistent with what we've seen before.

      Joe's cnamedtuple is about 40x faster for class creation than the current implementation, and my PR only speeds class creation up by 4x. That difference is big enough that I think we should seriously consider using the C implementation.

    18. methane commented on Jul 19, 2017

      @methane
      MemberAuthor

      I want to focus on pure Python implementation in this issue.

      While "40x faster" is more 10x faster than "4x faster", C implementation
      can boost only CPython and makes maintenance more harder.

      And sometimes "more 10x faster" is not so important.
      For example, say application startup takes 1sec and namedtuple
      creation took 0.4sec of the 1sec:

      4x faster: 1sec -> 0.7sec (-30%)
      40x faster: 1sec -> 0.61sec (-39%)

      In this case, "4x faster" reduces 0.3sec and "more 10x faster" reduces
      only 0.09sec.

      Of course, 1.9x faster attribute access (http://bugs.python.org/issue28638#msg298499) is attractive.
      But this issue is too long already.

    19. giampaolo commented on Jul 19, 2017

      @giampaolo
      Contributor

      While "40x faster" is more 10x faster than "4x faster", C
      implementation can boost only CPython and makes maintenance more harder.

      As a counter argument against "let's not do it because it'll be harder to maintain" I'd like to point out that namedtuple API is already kind of over engineered (see: "verbose", "rename", "module" and "_source") and as such it seems likely it will remain pretty much the same in the future. So why not treat namedtuple like any other basic data structure, boost its internal implementation and simply use the existing unit tests to make sure there are no regressions? It seems the same barrier does not apply to tuples, lists and sets.

      Of course, 1.9x faster attribute access (http://bugs.python.org/issue28638#msg298499) is attractive.

      It is indeed and it makes a huge difference in situations like busy loops. E.g. in case of asyncio 1.9x faster literally means being able to serve twice the number of reqs/sec:

      fileobj, (reader, writer) = key.fileobj, key.data

    20. methane commented on Jul 19, 2017

      @methane
      MemberAuthor

      I didn't say "let's not do it".
      I just want to focus on pure Python implementation at this issue,
      because this thread is too long already.
      Feel free to open new issue about C implementation.

      Even if C implementation is added later, pure Python optimization
      can boost PyPy performance. (#2736 (comment))

    21. vstinner commented on Jul 19, 2017

      @vstinner
      Member

      General note about this issue: while the issie title is "Optimize namedtuple creation", it would be *nice* to not only optimization the creation but also attribute access by name:
      http://bugs.python.org/issue28638#msg298499

      Maybe we can have a very fast C implementation using structseq, and a fast Python implementation (faster than the current Python implementation) fallback for non-CPython.

    22. gvanrossum commented on Jul 19, 2017

      @gvanrossum
      Member

      Yeah, it looks like the standard _pickle and pickle solution would work
      here.

    23. rhettinger commented on Jul 20, 2017

      @rhettinger
      Contributor

      it would be *nice* to not only optimization the creation
      but also attribute access by name

      FWIW, once the property/itemgetter pair are instantiated in the NT class, the actual lookup runs through them at C speed (no pure python steps). There is not much fluff here.

    24. MojoVampire commented on Sep 8, 2017

      MojoVampiremannequin
      Mannequin

      Side-note: Some of the objections to a C level namedtuple implementation appear to be based on the maintenance hurdle, and other have noted that a structseq-based namedtuple might be an option. I have previously attempted to write a C replacement for namedtuple that dynamically created a StructSequence. I ran into a roadblock due to PyStructSequence_NewType (the API that exists to allow creation of runtime defined structseq) being completely broken (bpo-28709).

      If the struct sequence API was fixed, it should be a *lot* easier to implement a C level namedtuple with minimal work, removing (some) of the maintenance objections by simply reducing the amount of custom code involved.

      The testnewtype.c code attached to bpo-28709 (that demonstrates the bug) is 66 lines of code, and implements a basic C level namedtuple creator function (full support omitted for brevity, but aside from _source, most of it would be easy). I'd expect a finished version to be low three digit lines of custom code, a third or less of what the cnamedtuple project needed to write the whole thing from scratch.

    25. serhiy-storchaka commented on Sep 10, 2017

      @serhiy-storchaka
      Member

      Microbenchmark for caching docstrings:

      $ ./python -m perf timeit -s "from collections import namedtuple; names = ['field%d' % i for i in range(1000)]" -- "namedtuple('A', names)"

      With sys.intern(): Mean +- std dev: 3.57 ms +- 0.05 ms
      With Python-level caching: Mean +- std dev: 3.25 ms +- 0.05 ms

    26. rhettinger commented on Sep 10, 2017

      @rhettinger
      Contributor

      New changeset 8b57d73 by Raymond Hettinger in branch 'master':
      bpo-28638: Optimize namedtuple() creation time by minimizing use of exec() (bpo-3454)
      8b57d73

    27. transferred this issue fromon Apr 10, 2022
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Metadata

    Metadata

    Assignees

    Labels

    3.7 (EOL)performancestdlib

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions