<br><br><div class="gmail_quote">On Fri, Jan 16, 2009 at 8:39 AM, Per Freem <span dir="ltr"><<a href="mailto:perfreem@yahoo.com">perfreem@yahoo.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
hello<br>
<br>
i have an optimization questions about python. i am iterating through<br>
a file and counting the number of repeated elements. the file has on<br>
the order<br>
of tens of millions elements...<br><br>
<br>
for line in file:<br>
  try:<br>
    elt = MyClass(line)# extract elt from line...<br>
    my_dict[elt] += 1<br>
  except KeyError:<br>
    my_dict[elt] = 1<br>
<br><br>
class MyClass<br>
<br>
  def __str__(self):<br>
    return "%s-%s-%s" %(self.field1, self.field2, self.field3)<br>
<br>
  def __repr__(self):<br>
    return str(self)<br>
<br>
  def __hash__(self):<br>
    return hash(str(self))<br>
<br>
<br>
is there anything that can be done to speed up this simply code? right<br>
now it is taking well over 15 minutes to process, on a 3 Ghz machine<br>
with lots of RAM (though this is all taking CPU power, not RAM at this<br>
point.)<br>
<br>
any general advice on how to optimize large dicts would be great too<br>
<br>
thanks for your help.<br>
<font color="#888888">--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</font></blockquote></div>Hello, <div><br></div><div>You can get a large speedup by removing the need to instantiate a new MyClass instance on </div><div>each iteration of your loop.</div><div>Instead define one MyClass with an 'interpret' method that would be called instead of MyClass()</div>
<div>interpret would return the string '%s-%s-%s' % (self.field1 etc..)</div><div><br></div><div>i.e </div><div><br></div><div>myclass = MyClass()</div><div>interpret = myclass.interpret</div><div><br></div><div><span class="Apple-style-span" style="border-collapse: collapse; ">for line in file:<br>
 <br> elt = interpet(line)# extract elt from line...</span></div><div><span class="Apple-style-span" style="border-collapse: collapse; "> try:<br>   my_dict[elt] += 1<br> except KeyError:<br>   my_dict[elt] = 1</span><br>
</div><div><span class="Apple-style-span" style="border-collapse: collapse;"><br></span></div><div><span class="Apple-style-span" style="border-collapse: collapse;">The speed up is on the order of 10 on my machine.</span></div>
<div><span class="Apple-style-span" style="border-collapse: collapse;"><br></span></div><div><span class="Apple-style-span" style="border-collapse: collapse;"><br></span></div><div><span class="Apple-style-span" style="border-collapse: collapse;">Cheers,</span></div>