<div dir="ltr">On 29 July 2013 12:46, Stefan Behnel <span dir="ltr"><<a href="mailto:stefan_ml@behnel.de" target="_blank">stefan_ml@behnel.de</a>></span> wrote:<br><div class="gmail_extra"><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">


Steven D'Aprano, 28.07.2013 22:51:<br>
<div>> Calling Counter ends up calling essentially this code:<br>
><br>
> for elem in iterable:<br>
>     self[elem] = self.get(elem, 0) + 1<br>
><br>
> (although micro-optimized), where "iterable" is your data (lines).<br>
> Calling the get method has higher overhead than dict[key], that will also<br>
> contribute.<br>
<br>
</div>It comes with a C accelerator (at least in Py3.4dev), but it seems like<br>
that stumbles a bit over its own feet. The accelerator function special<br>
cases the (exact) dict type, but the Counter class is a subtype of dict and<br>
thus takes the generic path, which makes it benefit a bit less than possible.<br>
<br>
Look for _count_elements() in<br>
<br>
<a href="http://hg.python.org/cpython/file/tip/Modules/_collectionsmodule.c" target="_blank">http://hg.python.org/cpython/file/tip/Modules/_collectionsmodule.c</a><br>
<br>
Nevertheless, even the generic C code path looks fast enough in general. I<br>
think the problem is just that the OP used Python 2.7, which doesn't have<br>
this accelerator function.<br></blockquote><div><br></div><div># _count_elements({}, items), _count_elements(dict_subclass(), items), Counter(items), defaultdict(int) loop with exception handling</div><div># "items" is always 1m long with varying levels of repetition</div>

<div><br></div><div><div>>>> for items in randoms:</div><div>... <span class="" style="white-space:pre">   </span>helper.timeit(1), helper_subclass.timeit(1), counter.timeit(1), default.timeit(1)</div><div>... </div>

<div>(0.18816172199876746, 0.4679023139997298, 0.9684444869999425, 0.33518486200046027)</div><div>(0.2936601179990248, 0.6056111739999324, 1.1316078849995392, 0.46283868699902087)</div><div>(0.35396358400066674, 0.685048443998312, 1.2120939880005608, 0.5497965239992482)</div>

<div>(0.5337620789996436, 0.8658702100001392, 1.4507492869997805, 0.7772859329998028)</div><div>(0.745282343999861, 1.1455801379997865, 2.116569702000561, 1.3293145009993168)</div></div><div><br></div><div>:(</div><div><br>

</div><div>I have the helper but Counter is still slow. Is it not getting used for some reason? It's not even as fast as helper on a dict's (direct, no overridden methods) subclass.</div>
</div></div></div>