Repository navigation
Closed
Labels
3.7 (EOL)end of lifeperformancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directory
Description
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']Metadata
Metadata
Assignees
Labels
3.7 (EOL)end of lifeperformancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directory
Activity
methane commentedon Nov 8, 2016
I surprised how functools make import time slower.
And I find namedtuple makes it slower.
When I replaced
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
[-]Creating namedtuple is too slow[/-][+]Creating namedtuple is too slow to be used in common stdlib (e.g. functools)[/+]methane commentedon Nov 8, 2016
I feel this patch is safe enough to be landed in 3.6.
zhangyangyu commentedon Nov 8, 2016
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?
methane commentedon Nov 8, 2016
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.
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.
zhangyangyu commentedon Nov 8, 2016
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.
methane commentedon Nov 8, 2016
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.
Yes. Balance is important.
I want to hear more opinions from more other devs.
serhiy-storchaka commentedon Nov 8, 2016
What is the main culprit, importing the collections module or compiling a named tuple?
serhiy-storchaka commentedon Nov 8, 2016
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.
methane commentedon Nov 8, 2016
In this time, later.
But collections module takes 1+ ms to import too.
I'll try to optimize it.
Make sense.
What "precompiled class" means? pyc file? or source string to be
executed?
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
serhiy-storchaka commentedon Nov 8, 2016
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.
50 remaining items
giampaolo commentedon Jul 18, 2017
I've just filed a ticket for this: llllllllll/cnamedtuple#7
llllllllll commentedon Jul 19, 2017
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.
JelleZijlstra commentedon Jul 19, 2017
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:
With unpatched CPython master I get:
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:
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.
JelleZijlstra commentedon Jul 19, 2017
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.
methane commentedon Jul 19, 2017
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.
giampaolo commentedon Jul 19, 2017
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.
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:
cpython/Lib/asyncio/selector_events.py
Line 523 in 3e2ad8e
methane commentedon Jul 19, 2017
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))
vstinner commentedon Jul 19, 2017
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.
gvanrossum commentedon Jul 19, 2017
Yeah, it looks like the standard
_pickleandpicklesolution would workhere.
rhettinger commentedon Jul 20, 2017
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.
MojoVampire commentedon Sep 8, 2017
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.
serhiy-storchaka commentedon Sep 10, 2017
Microbenchmark for caching docstrings:
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
rhettinger commentedon Sep 10, 2017
New changeset 8b57d73 by Raymond Hettinger in branch 'master':
bpo-28638: Optimize namedtuple() creation time by minimizing use of exec() (bpo-3454)
8b57d73