title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
WxPython differences between Windows and Linux
916,987
<p>The tutorials I've found on WxPython all use examples from Linux, but there seem to be differences in some details.</p> <p>For example, in Windows a Panel behind the widgets is mandatory to show the background properly. Additionally, some examples that look fine in the tutorials don't work in my computer.</p> <p>So, do you know what important differences are there, or maybe a good tutorial that is focused on Windows?</p> <p><b>EDIT: </b> I just remembered this: Does anybody know why when subclassing wx.App an OnInit() method is required, rather than the more logical <code>__init__</code>()?</p>
1
2009-05-27T17:16:34Z
935,519
<p>I find a number of small differences, but don't remember all of them. Here are two:</p> <p>1) The layout can be slightly different, for example, causing things to not completely fit in the window in one OS when the do in the other. I haven't investigated the reasons for this, but it happens most often when I use positions rather than sizers to arrange things.</p> <p>2) I have to explicitly call <code>Refresh</code> more in Windows. For example, if you place one panel over another, you won't see it the top panel in Windows until you call Refresh.</p> <p>I general, I write apps in Linux and run them in Windows, and things work similarly enough so this is a reasonable approach, but it's rare for me when something runs perfectly straight out of the gate after an OS switch.</p>
0
2009-06-01T16:11:54Z
[ "python", "windows", "linux", "user-interface", "wxpython" ]
Sorting a tuple that contains lists
917,202
<p>I have a similar question to <a href="http://stackoverflow.com/questions/222752/sorting-a-tuple-that-contains-tuples">this one</a> but instead my tuple contains lists, as follows:</p> <pre><code>mytuple = ( ["tomato", 3], ["say", 2], ["say", 5], ["I", 4], ["you", 1], ["tomato", 6], ) </code></pre> <p>What's the most efficient way of sorting this?</p>
0
2009-05-27T18:09:44Z
917,225
<p>You will have to instantiate a new tuple, unfortunately: something like</p> <pre><code>mytuple = sorted(mytuple) </code></pre> <p>should do the trick. <code>sorted</code> won't return a tuple, though. wrap the call in <code>tuple()</code> if you need that. This could potentially be costly if the data set is long.</p> <p>If you need to set on the second element in the sublists, you can use the <code>key</code> parameter to the <code>sorted</code> function. You'll need a helper function for that: </p> <pre><code>mytuple = sorted(mytuple, key=lambda row: row[1]) </code></pre>
1
2009-05-27T18:13:59Z
[ "python", "list", "sorting", "tuples" ]
Sorting a tuple that contains lists
917,202
<p>I have a similar question to <a href="http://stackoverflow.com/questions/222752/sorting-a-tuple-that-contains-tuples">this one</a> but instead my tuple contains lists, as follows:</p> <pre><code>mytuple = ( ["tomato", 3], ["say", 2], ["say", 5], ["I", 4], ["you", 1], ["tomato", 6], ) </code></pre> <p>What's the most efficient way of sorting this?</p>
0
2009-05-27T18:09:44Z
917,226
<p>The technique used in the accepted answer to that question (<code>sorted(..., key=itemgetter(...))</code>) should work with any iterable of this kind. Based on the data you present here, I think the exact solution presented there is what you want.</p>
1
2009-05-27T18:14:09Z
[ "python", "list", "sorting", "tuples" ]
Sorting a tuple that contains lists
917,202
<p>I have a similar question to <a href="http://stackoverflow.com/questions/222752/sorting-a-tuple-that-contains-tuples">this one</a> but instead my tuple contains lists, as follows:</p> <pre><code>mytuple = ( ["tomato", 3], ["say", 2], ["say", 5], ["I", 4], ["you", 1], ["tomato", 6], ) </code></pre> <p>What's the most efficient way of sorting this?</p>
0
2009-05-27T18:09:44Z
917,238
<p>You can get a sorted tuple easy enough:</p> <pre><code>&gt;&gt;&gt; sorted(mytuple) [['I', 4], ['say', 2], ['say', 5], ['tomato', 3], ['tomato', 6], ['you', 1]] </code></pre> <p>This will sort based on the items in the list. If the first two match, it compares the second, etc.</p> <p>If you have a different criteria, you can provide a comparison function.</p> <p><strong>Updated:</strong> As a commenter noted, this returns a list. You can get another tuple like so:</p> <pre><code>&gt;&gt;&gt; tuple(sorted(mytuple)) (['I', 4], ['say', 2], ['say', 5], ['tomato', 3], ['tomato', 6], ['you', 1]) </code></pre>
7
2009-05-27T18:16:04Z
[ "python", "list", "sorting", "tuples" ]
Sorting a tuple that contains lists
917,202
<p>I have a similar question to <a href="http://stackoverflow.com/questions/222752/sorting-a-tuple-that-contains-tuples">this one</a> but instead my tuple contains lists, as follows:</p> <pre><code>mytuple = ( ["tomato", 3], ["say", 2], ["say", 5], ["I", 4], ["you", 1], ["tomato", 6], ) </code></pre> <p>What's the most efficient way of sorting this?</p>
0
2009-05-27T18:09:44Z
917,615
<p>You cannot sort a tuple. </p> <p>What you can do is use <a href="http://docs.python.org/library/functions.html?highlight=sorted#sorted">sorted()</a> which will not sort the tuple, but will create a sorted list from your tuple. If you really need a sorted tuple, you can then cast the return from sorted as a tuple:</p> <pre><code>mytuple = tuple(sorted(mytuple, key=lambda row: row[1])) </code></pre> <p>This can be a waste of memory since you are creating a list and then discarding it (and also discarding the original tuple). Chances are you don't need a tuple. Much more efficient would be to start with a list and sort that. </p>
5
2009-05-27T19:38:07Z
[ "python", "list", "sorting", "tuples" ]
Does Ruby have an equivalent of Python's twisted framework as a networking abstraction layer?
917,369
<p>From my understanding, Python's twisted framework provides a higher-level abstraction for networking communications (?). </p> <p>I am looking for a Ruby equivalent of twisted to use in a Rails application.</p>
6
2009-05-27T18:44:57Z
917,538
<p>Take a look at <a href="http://eventmachine.rubyforge.org/">EventMachine</a>. It's not as extensive as Twisted but it's built around the same concepts of event-driven network programming.</p>
7
2009-05-27T19:17:45Z
[ "python", "ruby-on-rails", "ruby", "twisted" ]
how to write nslookup programmatically?
917,619
<p>instead of using exec in our script to do an nslookup, is there an easy way to write it programmatically in PHP, Python, or Ruby?</p>
2
2009-05-27T19:39:03Z
917,650
<p>For Python see <a href="http://small-code.blogspot.com/2008/05/nslookup-in-python.html" rel="nofollow">http://small-code.blogspot.com/2008/05/nslookup-in-python.html</a> . For much richer functionality, also in Python, see <a href="http://www.dnspython.org/" rel="nofollow">http://www.dnspython.org/</a> .</p>
1
2009-05-27T19:44:07Z
[ "php", "python", "ruby", "networking", "nslookup" ]
how to write nslookup programmatically?
917,619
<p>instead of using exec in our script to do an nslookup, is there an easy way to write it programmatically in PHP, Python, or Ruby?</p>
2
2009-05-27T19:39:03Z
917,651
<p><a href="http://www.ruby-doc.org/stdlib/libdoc/socket/rdoc/classes/Socket.html#M004531" rel="nofollow">Socket Class</a> in Ruby. See this <a href="http://stackoverflow.com/questions/2993/reverse-dns-in-ruby/3012#3012">answer</a>.</p>
1
2009-05-27T19:44:15Z
[ "php", "python", "ruby", "networking", "nslookup" ]
how to write nslookup programmatically?
917,619
<p>instead of using exec in our script to do an nslookup, is there an easy way to write it programmatically in PHP, Python, or Ruby?</p>
2
2009-05-27T19:39:03Z
917,658
<p>Yes, although the function names might not be what you expect.</p> <p>Since the Python and Ruby answers are already posted, here is an PHP example:</p> <pre><code>$ip = gethostbyname('www.example.com'); $hostname = gethostbyaddr('127.0.0.1'); </code></pre>
4
2009-05-27T19:45:41Z
[ "php", "python", "ruby", "networking", "nslookup" ]
how to write nslookup programmatically?
917,619
<p>instead of using exec in our script to do an nslookup, is there an easy way to write it programmatically in PHP, Python, or Ruby?</p>
2
2009-05-27T19:39:03Z
917,691
<p>For PHP, you can use <a href="http://php.net/gethostbyname" rel="nofollow">gethostbyname</a> and <a href="http://php.net/gethostbyaddr" rel="nofollow">gethostbyaddr</a>.</p> <p>For Python, import the socket module and again use <a href="http://docs.python.org/library/socket.html#socket.gethostbyname" rel="nofollow">gethostbyname</a> and <a href="http://docs.python.org/library/socket.html#socket.gethostbyaddr" rel="nofollow">gethostbyaddr</a>.</p>
1
2009-05-27T19:51:04Z
[ "php", "python", "ruby", "networking", "nslookup" ]
how to write nslookup programmatically?
917,619
<p>instead of using exec in our script to do an nslookup, is there an easy way to write it programmatically in PHP, Python, or Ruby?</p>
2
2009-05-27T19:39:03Z
36,620,700
<pre><code>$ip = gethostbyname('www.example.com'); </code></pre> <p>This will work but please be aware that it will be affected if the user changes their hosts file. You can't rely on it. </p>
0
2016-04-14T10:42:27Z
[ "php", "python", "ruby", "networking", "nslookup" ]
Reinstall /Library/Python on OS X Leopard
917,876
<p>I accidentally removed /Library/Python on OS X Leopard. How can I reinstall that?</p>
0
2009-05-27T20:31:50Z
917,890
<p>If you'd like, I'll create a tarball from a pristine installation. I'm using MacOSX 10.5.7, and only 12K.</p>
1
2009-05-27T20:34:52Z
[ "python", "osx", "osx-leopard", "reinstall" ]
Reinstall /Library/Python on OS X Leopard
917,876
<p>I accidentally removed /Library/Python on OS X Leopard. How can I reinstall that?</p>
0
2009-05-27T20:31:50Z
917,896
<p>I'm using 10.4, but unless the installation changed dramatically in 10.5, <code>/Library/Python</code> is just a place to install local (user-installed) packages; the actual Python install is under <code>/System</code>. On 10.4, I have the following structure:</p> <pre><code>/Library/ Python/ 2.3/ README site-packages/ README </code></pre> <p>So just re-creating that structure may suffice. (But instead of <code>2.3</code>, use the version of Python installed on 10.5.)</p>
1
2009-05-27T20:36:08Z
[ "python", "osx", "osx-leopard", "reinstall" ]
Reinstall /Library/Python on OS X Leopard
917,876
<p>I accidentally removed /Library/Python on OS X Leopard. How can I reinstall that?</p>
0
2009-05-27T20:31:50Z
917,897
<p><code>/Library/Python</code> contains your python site-packages, which is the local software you've installed using commands like <code>python setup.py install</code>. The pieces here are third-party packages, not items installed by Apple - your actual Python installation is still safe in /System/Library/etc... </p> <p>In other words, the default OS leaves these directories mostly blank... nothing in there is critical (just a readme and a path file).</p> <p>In this case, you'll have to :</p> <ol> <li><p>Recreate the directory structure:</p></li> <li><p>Re-install your third-party libraries.</p></li> </ol> <p>The directory structure on a default OS X install is:</p> <blockquote> <p>/Library/Python/2.3/site-packages /Library/Python/2.5/site-packages</p> </blockquote>
1
2009-05-27T20:36:51Z
[ "python", "osx", "osx-leopard", "reinstall" ]
How do I filter by time in a date time field?
917,996
<p>In the model 'entered' is a datetime field. I want to query the data to find all entry's that where made between noon(start_time) and 5:00pm (end_time).</p> <pre><code>selected = Entry.objects.filter(entered__gte=start_time, entered__lte=end_time) </code></pre> <p>(as I expected)I get an error of:</p> <pre><code>"ValidationError: Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." </code></pre> <p>So I know I can use __year so I tried.</p> <pre><code>selected = Entry.objects.filter(entered__time__gte=start_time, entered__time__lte=end_time) </code></pre> <p>I get an error of:</p> <pre><code>"FieldError: Join on field 'start' not permitted. Did you misspell 'time' for the lookup type?" </code></pre>
5
2009-05-27T21:03:17Z
918,071
<p>I don't believe there's built-in support for this, but you can pass <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none">extra where-clause</a> parameters (warning: some possibility of introducing DB-dependent behaviour here).</p> <p>For example, on Postgres, something like:</p> <pre><code>Entry.objects.extra(where=['EXTRACT(hour from entered) &gt;= 12 and '\ 'EXTRACT(hour from entered) &lt; 17']) </code></pre> <p>If you're using potentially unsafe input to determine the values <code>12</code> and <code>17</code>, note that you can also specify a params option to extra that will ensure proper quoting and escaping, and then use the standard sql <code>%s</code> placeholders in your where statement.</p>
5
2009-05-27T21:21:34Z
[ "python", "django" ]
How do I filter by time in a date time field?
917,996
<p>In the model 'entered' is a datetime field. I want to query the data to find all entry's that where made between noon(start_time) and 5:00pm (end_time).</p> <pre><code>selected = Entry.objects.filter(entered__gte=start_time, entered__lte=end_time) </code></pre> <p>(as I expected)I get an error of:</p> <pre><code>"ValidationError: Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." </code></pre> <p>So I know I can use __year so I tried.</p> <pre><code>selected = Entry.objects.filter(entered__time__gte=start_time, entered__time__lte=end_time) </code></pre> <p>I get an error of:</p> <pre><code>"FieldError: Join on field 'start' not permitted. Did you misspell 'time' for the lookup type?" </code></pre>
5
2009-05-27T21:03:17Z
918,322
<p>Did you provide <a href="http://docs.python.org/library/datetime.html#datetime-objects" rel="nofollow">datetime objects</a> for <code>start_time</code> and <code>end_time</code>?</p> <p>A quick try-out:</p> <pre><code>class Entry(models.Model): entered = models.DateTimeField() &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; Entry(entered = datetime.now()).save() &gt;&gt;&gt; Entry.objects.filter(entered__lte = datetime.now()) [&lt;Entry: Entry object&gt;] &gt;&gt;&gt; Entry.objects.filter(entered__gte = datetime.now()) [] &gt;&gt;&gt; Entry.objects.filter(entered__gte = datetime.now(), entered__lte=datetime(2009,11,1,0,0)) [&lt;Entry: Entry object&gt;] </code></pre>
0
2009-05-27T22:31:01Z
[ "python", "django" ]
How do I filter by time in a date time field?
917,996
<p>In the model 'entered' is a datetime field. I want to query the data to find all entry's that where made between noon(start_time) and 5:00pm (end_time).</p> <pre><code>selected = Entry.objects.filter(entered__gte=start_time, entered__lte=end_time) </code></pre> <p>(as I expected)I get an error of:</p> <pre><code>"ValidationError: Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." </code></pre> <p>So I know I can use __year so I tried.</p> <pre><code>selected = Entry.objects.filter(entered__time__gte=start_time, entered__time__lte=end_time) </code></pre> <p>I get an error of:</p> <pre><code>"FieldError: Join on field 'start' not permitted. Did you misspell 'time' for the lookup type?" </code></pre>
5
2009-05-27T21:03:17Z
921,083
<p>Using SQLite as an example, a relatively clean and generic solution would be:</p> <pre><code>Entry.objects.extra(where=["time(entered) between '%s' and '%s'"], params=[start_time.strftime("%H:%M"), end_time.strftime("%H:%M")]) </code></pre>
3
2009-05-28T14:19:16Z
[ "python", "django" ]
How do I filter by time in a date time field?
917,996
<p>In the model 'entered' is a datetime field. I want to query the data to find all entry's that where made between noon(start_time) and 5:00pm (end_time).</p> <pre><code>selected = Entry.objects.filter(entered__gte=start_time, entered__lte=end_time) </code></pre> <p>(as I expected)I get an error of:</p> <pre><code>"ValidationError: Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." </code></pre> <p>So I know I can use __year so I tried.</p> <pre><code>selected = Entry.objects.filter(entered__time__gte=start_time, entered__time__lte=end_time) </code></pre> <p>I get an error of:</p> <pre><code>"FieldError: Join on field 'start' not permitted. Did you misspell 'time' for the lookup type?" </code></pre>
5
2009-05-27T21:03:17Z
921,139
<p>You could filter in python instead using the db's mechanisms:</p> <pre><code>for e in Entry.objects.all(): if i.entered.hour&gt;= 9 and i.entered.hour &lt; 17 :# or break down to minutes/seconds list.append(e) </code></pre> <p>but both solutions are ugly, i think.</p> <p>Steve, you have to decide, what is less ugly for you:</p> <ul> <li>processsing a lot of data in a for-loop,</li> <li>or use .extra(..) and by-passing the orm-system</li> </ul>
2
2009-05-28T14:28:59Z
[ "python", "django" ]
How do I filter by time in a date time field?
917,996
<p>In the model 'entered' is a datetime field. I want to query the data to find all entry's that where made between noon(start_time) and 5:00pm (end_time).</p> <pre><code>selected = Entry.objects.filter(entered__gte=start_time, entered__lte=end_time) </code></pre> <p>(as I expected)I get an error of:</p> <pre><code>"ValidationError: Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." </code></pre> <p>So I know I can use __year so I tried.</p> <pre><code>selected = Entry.objects.filter(entered__time__gte=start_time, entered__time__lte=end_time) </code></pre> <p>I get an error of:</p> <pre><code>"FieldError: Join on field 'start' not permitted. Did you misspell 'time' for the lookup type?" </code></pre>
5
2009-05-27T21:03:17Z
13,894,806
<p>I suggest filter <code>x&lt;=arg</code> and exclude <code>x&gt;=arg2</code>.</p>
0
2012-12-15T18:10:45Z
[ "python", "django" ]
How do I filter by time in a date time field?
917,996
<p>In the model 'entered' is a datetime field. I want to query the data to find all entry's that where made between noon(start_time) and 5:00pm (end_time).</p> <pre><code>selected = Entry.objects.filter(entered__gte=start_time, entered__lte=end_time) </code></pre> <p>(as I expected)I get an error of:</p> <pre><code>"ValidationError: Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." </code></pre> <p>So I know I can use __year so I tried.</p> <pre><code>selected = Entry.objects.filter(entered__time__gte=start_time, entered__time__lte=end_time) </code></pre> <p>I get an error of:</p> <pre><code>"FieldError: Join on field 'start' not permitted. Did you misspell 'time' for the lookup type?" </code></pre>
5
2009-05-27T21:03:17Z
21,847,795
<p>You can use range to filter in between. I found this the best way to filter since SQL does filtering better than Django. </p> <pre><code>fromRange=datetime.datetime.strptime(request.GET.get('from'),'%Y-%m-%dT%H:%M:%S.%fZ') toRange=datetime.datetime.strptime(request.GET.get('to'),'%Y-%m-%dT%H:%M:%S.%fZ') entry = Entry.objects.filter(entryTime__range=(fromRange,toRange)) </code></pre>
-1
2014-02-18T08:17:43Z
[ "python", "django" ]
How do I filter by time in a date time field?
917,996
<p>In the model 'entered' is a datetime field. I want to query the data to find all entry's that where made between noon(start_time) and 5:00pm (end_time).</p> <pre><code>selected = Entry.objects.filter(entered__gte=start_time, entered__lte=end_time) </code></pre> <p>(as I expected)I get an error of:</p> <pre><code>"ValidationError: Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." </code></pre> <p>So I know I can use __year so I tried.</p> <pre><code>selected = Entry.objects.filter(entered__time__gte=start_time, entered__time__lte=end_time) </code></pre> <p>I get an error of:</p> <pre><code>"FieldError: Join on field 'start' not permitted. Did you misspell 'time' for the lookup type?" </code></pre>
5
2009-05-27T21:03:17Z
35,946,485
<p>I just figured out a solution for a similar use case – perhaps someone finds this useful:</p> <p>In my case, I have Availability and Constraint models like so (simplified):</p> <pre><code>class Availability(...): start = models.DateTimeField() end = models.DateTimeField() class Constraint(...): from = models.TimeField() to = models.TimeField() </code></pre> <p>I wanted to find availabilities that don't violate any constraints.</p> <p>With Postgres, this worked for me:</p> <pre><code>Availability.objects.extra( where=['NOT (start::time, "end"::time) OVERLAPS (\'{0}\'::time, \'{1}\'::time)'.format( from.strftime("%H:%M"), to.strftime("%H:%M") )] ) </code></pre> <p>Note how you can cast <code>DateTime</code> to <code>Time</code> (or rather <code>timestamp</code> to <code>time without timezone</code> in Postgres terms) with <code>::time</code> and then use <code>OVERLAPS</code> to compare the time ranges. </p> <p>And in regards to the original question, you can also do:</p> <pre><code>Availability.objects.extra( where=['start::time BETWEEN \'{0}\'::time AND \'{1}\'::time AND "end"::time BETWEEN \'{0}\'::time AND \'{1}\'::time'.format( from.strftime("%H:%M"), to.strftime("%H:%M") )] ) </code></pre>
0
2016-03-11T17:36:07Z
[ "python", "django" ]
Is there a way in Python to index a list of containers (tuples, lists, dictionaries) by an element of a container?
918,076
<p>I have been poking around for a recipe / example to index a list of tuples without taking a modification of the decorate, sort, undecorate approach. </p> <p>For example:</p> <pre><code>l=[(a,b,c),(x,c,b),(z,c,b),(z,c,d),(a,d,d),(x,d,c) . . .] </code></pre> <p>The approach I have been using is to build a dictionary using defaultdict of the second element</p> <pre><code>from collections import defaultdict tdict=defaultdict(int) for myTuple in l: tdict[myTuple[1]]+=1 </code></pre> <p>Then I have to build a list consisting of only the second item in the tuple for each item in the list. While there are a number of ways to get there a simple approach is to:</p> <pre><code>tempList=[myTuple[1] for myTuple in l] </code></pre> <p>and then generate an index of each item in tdict </p> <pre><code>indexDict=defaultdict(dict) for key in tdict: indexDict[key]['index']=tempList.index(key) </code></pre> <p>Clearly this does not seem very Pythonic. I have been trying to find examples or insights thinking that I should be able to use something magical to get the index directly. No such luck so far.</p> <p>Note, I understand that I can take my approach a little more directly and not generating tdict. </p> <p>output could be a dictionary with the index </p> <pre><code>indexDict={'b':{'index':0},'c':{'index':1},'d':{'index':4},. . .} </code></pre> <p>After learning a lot from Nadia's responses I think the answer is no.</p> <p>While her response works I think it is more complicated than needed. I would simply</p> <pre><code> def build_index(someList): indexDict={} for item in enumerate(someList): if item[1][1] not in indexDict: indexDict[item[1][1]]=item[0] return indexDict </code></pre>
1
2009-05-27T21:22:43Z
918,115
<p>If i think this is what you're asking...</p> <pre><code>l = ['asd', 'asdxzc'] d = {} for i, x in enumerate(l): d[x] = {'index': i} </code></pre>
0
2009-05-27T21:32:25Z
[ "python", "indexing", "list", "containers" ]
Is there a way in Python to index a list of containers (tuples, lists, dictionaries) by an element of a container?
918,076
<p>I have been poking around for a recipe / example to index a list of tuples without taking a modification of the decorate, sort, undecorate approach. </p> <p>For example:</p> <pre><code>l=[(a,b,c),(x,c,b),(z,c,b),(z,c,d),(a,d,d),(x,d,c) . . .] </code></pre> <p>The approach I have been using is to build a dictionary using defaultdict of the second element</p> <pre><code>from collections import defaultdict tdict=defaultdict(int) for myTuple in l: tdict[myTuple[1]]+=1 </code></pre> <p>Then I have to build a list consisting of only the second item in the tuple for each item in the list. While there are a number of ways to get there a simple approach is to:</p> <pre><code>tempList=[myTuple[1] for myTuple in l] </code></pre> <p>and then generate an index of each item in tdict </p> <pre><code>indexDict=defaultdict(dict) for key in tdict: indexDict[key]['index']=tempList.index(key) </code></pre> <p>Clearly this does not seem very Pythonic. I have been trying to find examples or insights thinking that I should be able to use something magical to get the index directly. No such luck so far.</p> <p>Note, I understand that I can take my approach a little more directly and not generating tdict. </p> <p>output could be a dictionary with the index </p> <pre><code>indexDict={'b':{'index':0},'c':{'index':1},'d':{'index':4},. . .} </code></pre> <p>After learning a lot from Nadia's responses I think the answer is no.</p> <p>While her response works I think it is more complicated than needed. I would simply</p> <pre><code> def build_index(someList): indexDict={} for item in enumerate(someList): if item[1][1] not in indexDict: indexDict[item[1][1]]=item[0] return indexDict </code></pre>
1
2009-05-27T21:22:43Z
918,160
<p>This will generate the result you want</p> <pre><code>dict((myTuple[1], index) for index, myTuple in enumerate(l)) &gt;&gt;&gt; l = [(1, 2, 3), (4, 5, 6), (1, 4, 6)] &gt;&gt;&gt; dict((myTuple[1], index) for index, myTuple in enumerate(l)) {2: 0, 4: 2, 5: 1} </code></pre> <p>And if you insist on using a dictionary to represent the index:</p> <pre><code>dict((myTuple[1], {'index': index}) for index, myTuple in enumerate(l)) </code></pre> <p>The result will be:</p> <pre><code>{2: {'index': 0}, 4: {'index': 2}, 5: {'index': 1}} </code></pre> <p><hr /></p> <p><strong>EDIT</strong> If you want to handle key collision then you'll have to extend the solution like this:</p> <pre><code>def build_index(l): indexes = [(myTuple[1], index) for index, myTuple in enumerate(l)] d = {} for e, index in indexes: d[e] = min(index, d.get(e, index)) return d &gt;&gt;&gt; l = [(1, 2, 3), (4, 5, 6), (1, 4, 6), (2, 4, 6)] &gt;&gt;&gt; build_index(l) {2: 0, 4: 2, 5: 1} </code></pre> <p><hr /></p> <p><strong>EDIT 2</strong></p> <p>And a more generalized and compact solution (in a similar definition to <a href="http://docs.python.org/library/functions.html?highlight=sorted#sorted" rel="nofollow">sorted</a>)</p> <pre><code>def index(l, key): d = {} for index, myTuple in enumerate(l): d[key(myTuple)] = min(index, d.get(key(myTuple), index)) return d &gt;&gt;&gt; index(l, lambda a: a[1]) {2: 0, 4: 2, 5: 1} </code></pre> <p>So the answer to your question is yes: There is a way in Python to index a list of containers (tuples, lists, dictionaries) by an element of a container without preprocessing. But your request of storing the result in a dictionary makes it impossible to be a one liner. But there is no preprocessing here. The list is iterated only once.</p>
5
2009-05-27T21:44:16Z
[ "python", "indexing", "list", "containers" ]
Relative paths in Python
918,154
<p>I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?</p>
71
2009-05-27T21:43:21Z
918,174
<p>See <a href="http://docs.python.org/library/sys.html#sys.path">sys.path</a> As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. </p> <p>Use this path as the root folder from which you <a href="http://docs.python.org/library/os.path.html#os.path.join">apply your relative path</a></p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; import os.path &gt;&gt;&gt; sys.path[0] 'C:\\Python25\\Lib\\idlelib' &gt;&gt;&gt; os.path.relpath(sys.path[0], "path_to_libs") # if you have python 2.6 &gt;&gt;&gt; os.path.join(sys.path[0], "path_to_libs") 'C:\\Python25\\Lib\\idlelib\\path_to_libs' </code></pre>
6
2009-05-27T21:47:16Z
[ "python", "relative-path", "path" ]
Relative paths in Python
918,154
<p>I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?</p>
71
2009-05-27T21:43:21Z
918,178
<p>In the file that has the script, you want to do something like this:</p> <pre><code>import os dir = os.path.dirname(__file__) filename = os.path.join(dir, '/relative/path/to/file/you/want') </code></pre> <p>This will give you the absolute path to the file you're looking for. Note that if you're using setuptools, you should probably use its <a href="http://peak.telecommunity.com/DevCenter/PythonEggs#accessing-package-resources">package resources API</a> instead.</p> <p><strong>UPDATE</strong>: I'm responding to a comment here so I can paste a code sample. :-)</p> <blockquote> <p>Am I correct in thinking that <code>__file__</code> is not always available (e.g. when you run the file directly rather than importing it)?</p> </blockquote> <p>I'm assuming you mean the <code>__main__</code> script when you mention running the file directly. If so, that doesn't appear to be the case on my system (python 2.5.1 on OS X 10.5.7):</p> <pre><code>#foo.py import os print os.getcwd() print __file__ #in the interactive interpreter &gt;&gt;&gt; import foo /Users/jason foo.py #and finally, at the shell: ~ % python foo.py /Users/jason foo.py </code></pre> <p>However, I do know that there are some quirks with <code>__file__</code> on C extensions. For example, I can do this on my Mac:</p> <pre><code>&gt;&gt;&gt; import collections #note that collections is a C extension in Python 2.5 &gt;&gt;&gt; collections.__file__ '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib- dynload/collections.so' </code></pre> <p>However, this raises an exception on my Windows machine.</p>
94
2009-05-27T21:47:50Z
[ "python", "relative-path", "path" ]
Relative paths in Python
918,154
<p>I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?</p>
71
2009-05-27T21:43:21Z
9,768,491
<p>you need <code>os.path.realpath</code> (sample below adds the parent directory to your path)</p> <pre><code>import sys,os sys.path.append(os.path.realpath('..')) </code></pre>
33
2012-03-19T10:24:27Z
[ "python", "relative-path", "path" ]
Relative paths in Python
918,154
<p>I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?</p>
71
2009-05-27T21:43:21Z
20,437,590
<p>Hi first of all you should understand functions <strong>os.path.abspath(path)</strong> and <strong>os.path.relpath(path)</strong> </p> <p>In short <strong>os.path.abspath(path)</strong> makes a <strong>relative path</strong> to <strong>absolute path</strong>. And if the path provided is itself a absolute path then the function returns the same path.</p> <p>similarly <strong>os.path.relpath(path)</strong> makes a <strong>absolute path</strong> to <strong>relative path</strong>. And if the path provided is itself a relative path then the function returns the same path.</p> <p><em><strong>Below example can let you understand the above concept properly</em></strong>:</p> <p>suppose i have a file <strong>input_file_list.txt</strong> which contains list of input files to be processed by my python script.</p> <p>D:\conc\input1.dic</p> <p>D:\conc\input2.dic</p> <p>D:\Copyioconc\input_file_list.txt</p> <p>If you see above folder structure, <strong>input_file_list.txt</strong> is present in <strong>Copyofconc</strong> folder and the files to be processed by the python script are present in <strong>conc</strong> folder</p> <p>But the content of the file <strong>input_file_list.txt</strong> is as shown below:</p> <p>..\conc\input1.dic</p> <p>..\conc\input2.dic</p> <p>And my python script is present in <strong>D:</strong> drive.</p> <p>And the relative path provided in the <strong>input_file_list.txt</strong> file are relative to the path of <strong>input_file_list.txt</strong> file.</p> <p>So when python script shall executed the current working directory (use <strong>os.getcwd()</strong> to get the path)</p> <p>As my relative path is relative to <strong>input_file_list.txt</strong>, that is <strong>"D:\Copyofconc"</strong>, i have to change the current working directory to <strong>"D:\Copyofconc"</strong>.</p> <p>So i have to use <strong>os.chdir('D:\Copyofconc')</strong>, so the current working directory shall be <strong>"D:\Copyofconc"</strong>.</p> <p>Now to get the files <strong>input1.dic</strong> and <strong>input2.dic</strong>, i will read the lines "..\conc\input1.dic" then shall use the command </p> <p><strong>input1_path= os.path.abspath('..\conc\input1.dic')</strong> (to change relative path to absolute path. Here as current working directory is "D:\Copyofconc", the file ".\conc\input1.dic" shall be accessed relative to "D:\Copyofconc")</p> <p>so <strong>input1_path</strong> shall be "D:\conc\input1.dic"</p>
-1
2013-12-07T04:30:00Z
[ "python", "relative-path", "path" ]
Relative paths in Python
918,154
<p>I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?</p>
71
2009-05-27T21:43:21Z
24,040,518
<p>I'm not sure if this applies to some of the older versions, but I believe Python 3.3 has native relative path support.</p> <p>For example the following code should create a text file in the same folder as the python script:</p> <pre><code>open("text_file_name.txt", "w+t") </code></pre> <p>(note that there shouldn't be a forward or backslash at the beginning if it's a relative path)</p>
-2
2014-06-04T14:41:21Z
[ "python", "relative-path", "path" ]
Relative paths in Python
918,154
<p>I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?</p>
71
2009-05-27T21:43:21Z
26,295,955
<p>An alternative which works for me: </p> <pre><code>this_dir = os.path.dirname(__file__) filename = os.path.realpath("{0}/relative/file.path".format(this_dir)) </code></pre>
0
2014-10-10T09:19:19Z
[ "python", "relative-path", "path" ]
Relative paths in Python
918,154
<p>I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?</p>
71
2009-05-27T21:43:21Z
32,973,614
<p>Consider my code:</p> <pre><code>import os def readFile(filename): filehandle = open(filename) print filehandle.read() filehandle.close() fileDir = os.path.dirname(os.path.realpath('__file__')) print fileDir #For accessing the file in the same folder filename = "same.txt" readFile(filename) #For accessing the file in a folder contained in the current folder filename = os.path.join(fileDir, 'Folder1.1/same.txt') readFile(filename) #For accessing the file in the parent folder of the current folder filename = os.path.join(fileDir, '../same.txt') readFile(filename) #For accessing the file inside a sibling folder. filename = os.path.join(fileDir, '../Folder2/same.txt') filename = os.path.abspath(os.path.realpath(filename)) print filename readFile(filename) </code></pre>
3
2015-10-06T15:17:35Z
[ "python", "relative-path", "path" ]
Relative paths in Python
918,154
<p>I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?</p>
71
2009-05-27T21:43:21Z
35,492,963
<p>Instead of using </p> <pre><code>import os dirname = os.path.dirname(__file__) filename = os.path.join(dirname, '/relative/path/to/file/you/want') </code></pre> <p>as in the accepted answer, it would be more robust to use:</p> <pre><code>import inspect import os dirname = os.path.dirname(os.path.abspath(inspect.stack()[0][1])) filename = os.path.join(dirname, '/relative/path/to/file/you/want') </code></pre> <p>because using __file__ will return the file from which the module was loaded, if it was loaded from a file, so if the file with the script is called from elsewhere, the directory returned will not be correct. </p> <p>These answers give more detail: <a href="http://stackoverflow.com/a/31867043/5542253">http://stackoverflow.com/a/31867043/5542253</a> and <a href="http://stackoverflow.com/a/50502/5542253">http://stackoverflow.com/a/50502/5542253</a></p>
2
2016-02-18T21:41:34Z
[ "python", "relative-path", "path" ]
Relative paths in Python
918,154
<p>I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?</p>
71
2009-05-27T21:43:21Z
36,209,089
<p>This code will return the absolute path to the main script.</p> <pre><code>import os def whereAmI(): return os.path.dirname(os.path.realpath(__import__("__main__").__file__)) </code></pre> <p>This will work even in a module.</p>
0
2016-03-24T20:03:52Z
[ "python", "relative-path", "path" ]
Relative paths in Python
918,154
<p>I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?</p>
71
2009-05-27T21:43:21Z
36,906,785
<p>As mentioned in the accepted answer <br></p> <pre><code>import os dir = os.path.dirname(__file__) filename = os.path.join(dir, '/relative/path/to/file/you/want') </code></pre> <p>I just want to add that</p> <blockquote> <p>the latter string can't begin with the backslash , infact no string should include a backslash</p> </blockquote> <p>It should be something like</p> <pre><code>import os dir = os.path.dirname(__file__) filename = os.path.join(dir, 'relative','path','to','file','you','want') </code></pre> <p>The accepted answer can be misleading in some cases , please refer to <a href="http://stackoverflow.com/questions/1945920/why-doesnt-os-path-join-work-in-this-case">this</a> link for details</p>
5
2016-04-28T06:22:44Z
[ "python", "relative-path", "path" ]
Swig / Python memory leak detected
918,180
<p>I have a very complicated class for which I'm attempting to make Python wrappers in SWIG. When I create an instance of the item in Python, however, I'm unable to initialize certain data members without receiving the message:</p> <pre><code>&gt;&gt;&gt; myVar = myModule.myDataType() swig/python detected a memory leak of type 'MyDataType *', no destructor found. </code></pre> <p>Does anyone know what I need to do to address this? Is there a flag I could be using to generate destructors?</p>
5
2009-05-27T21:48:03Z
918,814
<p>The error message is pretty clear to me, you need to define a destructor for this type. </p>
-7
2009-05-28T01:37:46Z
[ "python", "memory-leaks", "swig" ]
Swig / Python memory leak detected
918,180
<p>I have a very complicated class for which I'm attempting to make Python wrappers in SWIG. When I create an instance of the item in Python, however, I'm unable to initialize certain data members without receiving the message:</p> <pre><code>&gt;&gt;&gt; myVar = myModule.myDataType() swig/python detected a memory leak of type 'MyDataType *', no destructor found. </code></pre> <p>Does anyone know what I need to do to address this? Is there a flag I could be using to generate destructors?</p>
5
2009-05-27T21:48:03Z
920,988
<p>SWIG always generates destructor wrappers (unless <code>%nodefaultdtor</code> directive is used). However, in case where it doesn't know anything about a type, it will generate an opaque pointer wrapper, which will cause leaks (and the above message).</p> <p>Please check that <code>myDataType</code> is a type that is known by SWIG. Re-run SWIG with debug messages turned on and check for any messages similar to</p> <pre><code>Nothing is known about Foo base type - Bar. Ignored </code></pre> <p>Receiving a message as above means that SWIG doesn't know your type hierarchy to the full extent and thus operates on limited information - which could cause it to not generate a dtor.</p>
5
2009-05-28T13:59:41Z
[ "python", "memory-leaks", "swig" ]
Python unicode in Mac os X terminal
918,294
<p>Can someone explain to me this odd thing:</p> <p>When in python shell I type the following Cyrillic string:</p> <pre><code>&gt;&gt;&gt; print 'абвгд' абвгд </code></pre> <p>but when I type:</p> <pre><code>&gt;&gt;&gt; print u'абвгд' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128) </code></pre> <p>Since the first tring came out correctly, I reckon my OS X terminal can represent unicode, but it turns out it can't in the second case. Why ?</p>
7
2009-05-27T22:17:54Z
918,312
<p>A unicode object needs to be encoded before it can be displayed on some consoles. Try</p> <pre><code>u'абвгд'.encode() </code></pre> <p>instead to encode the unicode to a string object (most likely using utf8 as a default encoding, but depends on your python config)</p>
0
2009-05-27T22:28:32Z
[ "python", "osx", "unicode", "terminal" ]
Python unicode in Mac os X terminal
918,294
<p>Can someone explain to me this odd thing:</p> <p>When in python shell I type the following Cyrillic string:</p> <pre><code>&gt;&gt;&gt; print 'абвгд' абвгд </code></pre> <p>but when I type:</p> <pre><code>&gt;&gt;&gt; print u'абвгд' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128) </code></pre> <p>Since the first tring came out correctly, I reckon my OS X terminal can represent unicode, but it turns out it can't in the second case. Why ?</p>
7
2009-05-27T22:17:54Z
918,321
<p>Also, make sure the terminal encoding is set to Unicode/UTF-8 (and not ascii, which seems to be your setting):</p> <p><a href="http://www.rift.dk/news.php?item.7.6" rel="nofollow">http://www.rift.dk/news.php?item.7.6</a></p>
2
2009-05-27T22:30:55Z
[ "python", "osx", "unicode", "terminal" ]
Python unicode in Mac os X terminal
918,294
<p>Can someone explain to me this odd thing:</p> <p>When in python shell I type the following Cyrillic string:</p> <pre><code>&gt;&gt;&gt; print 'абвгд' абвгд </code></pre> <p>but when I type:</p> <pre><code>&gt;&gt;&gt; print u'абвгд' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128) </code></pre> <p>Since the first tring came out correctly, I reckon my OS X terminal can represent unicode, but it turns out it can't in the second case. Why ?</p>
7
2009-05-27T22:17:54Z
918,364
<p>In addition to ensuring your OS X terminal is set to UTF-8, you may wish to set your python sys default encoding to UTF-8 or better. Create a file in <code>/Library/Python/2.5/site-packages</code> called <code>sitecustomize.py</code>. In this file put:</p> <pre><code>import sys sys.setdefaultencoding('utf-8') </code></pre> <p>The <code>setdefaultencoding</code> method is available only by the site module, and is removed from the <a href="http://docs.python.org/library/sys.html#module-sys">sys namespace once startup has completed</a>. As such, you'll need to start a new python interpreter for the change to take effect. You can verify the current default coding at any time after startup with <code>sys.getdefaultencoding()</code>.</p> <p>If the characters aren't already unicode and you need to convert them, use the <code>decode</code> method on a string in order to decode the text from some other charset into unicode... best to specify which charset:</p> <pre><code>s = 'абвгд'.decode('some_cyrillic_charset') # makes the string unicode print s.encode('utf-8') # transform the unicode into utf-8, then print it </code></pre>
8
2009-05-27T22:52:42Z
[ "python", "osx", "unicode", "terminal" ]
Python unicode in Mac os X terminal
918,294
<p>Can someone explain to me this odd thing:</p> <p>When in python shell I type the following Cyrillic string:</p> <pre><code>&gt;&gt;&gt; print 'абвгд' абвгд </code></pre> <p>but when I type:</p> <pre><code>&gt;&gt;&gt; print u'абвгд' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128) </code></pre> <p>Since the first tring came out correctly, I reckon my OS X terminal can represent unicode, but it turns out it can't in the second case. Why ?</p>
7
2009-05-27T22:17:54Z
918,425
<pre><code>&gt;&gt;&gt; print 'абвгд' абвгд </code></pre> <p>When you type in some characters, your terminal decides how these characters are represented to the application. Your terminal might give the characters to the application encoded as utf-8, ISO-8859-5 or even something that only your terminal understands. Python gets these characters as some sequence of bytes. Then python prints out these bytes as they are, and your terminal interprets them in some way to display characters. Since your terminal usually interprets the bytes the same way as it encoded them before, everything is displayed like you typed it in.</p> <pre><code>&gt;&gt;&gt; u'абвгд' </code></pre> <p>Here you type in some characters that arrive at the python interpreter as a sequence of bytes, maybe encoded in some way by the terminal. With the <code>u</code> prefix python tries to convert this data to unicode. To do this correctly python has to known what encoding your terminal uses. In your case it looks like Python guesses your terminals encoding would be ASCII, but the received data doesn't match that, so you get an encoding error.</p> <p>The straight forward way to create unicode strings in an interactive session would therefore be something like this this:</p> <pre><code>&gt;&gt;&gt; us = 'абвгд'.decode('my-terminal-encoding') </code></pre> <p>In files you can also specify the encoding of the file with a special mode line:</p> <pre><code># -*- encoding: ISO-8859-5 -*- us = u'абвгд' </code></pre> <p>For other ways to set the default input encoding you can look at <code>sys.setdefaultencoding(...)</code> or <code>sys.stdin.encoding</code>.</p>
16
2009-05-27T23:12:40Z
[ "python", "osx", "unicode", "terminal" ]
Python unicode in Mac os X terminal
918,294
<p>Can someone explain to me this odd thing:</p> <p>When in python shell I type the following Cyrillic string:</p> <pre><code>&gt;&gt;&gt; print 'абвгд' абвгд </code></pre> <p>but when I type:</p> <pre><code>&gt;&gt;&gt; print u'абвгд' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128) </code></pre> <p>Since the first tring came out correctly, I reckon my OS X terminal can represent unicode, but it turns out it can't in the second case. Why ?</p>
7
2009-05-27T22:17:54Z
918,437
<p>'абвгд' is not a unicode string</p> <p>u'абвгд' is a unicode string</p> <p>You cannot print unicode strings without encoding them. When you are dealing with strings in your application you want to make sure that any input is decoded and any output in encoded. This way your application will deal only with unicode strings internally and output strings in UTF8.</p> <p>For reference:</p> <pre><code>&gt;&gt;&gt; 'абвгд'.decode('utf8') == u'абвгд' &gt;&gt;&gt; True </code></pre>
0
2009-05-27T23:14:40Z
[ "python", "osx", "unicode", "terminal" ]
Python unicode in Mac os X terminal
918,294
<p>Can someone explain to me this odd thing:</p> <p>When in python shell I type the following Cyrillic string:</p> <pre><code>&gt;&gt;&gt; print 'абвгд' абвгд </code></pre> <p>but when I type:</p> <pre><code>&gt;&gt;&gt; print u'абвгд' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128) </code></pre> <p>Since the first tring came out correctly, I reckon my OS X terminal can represent unicode, but it turns out it can't in the second case. Why ?</p>
7
2009-05-27T22:17:54Z
9,930,894
<p>As of Python 2.6, you can use the environment variable <code>PYTHONIOENCODING</code> to tell Python that your terminal is UTF-8 capable. The easiest way to make this permanent is by adding the following line to your <code>~/.bash_profile</code>:</p> <pre><code>export PYTHONIOENCODING=utf-8 </code></pre> <p><img src="http://i.stack.imgur.com/T3sID.png" alt="Terminal.app showing unicode output from Python"></p>
12
2012-03-29T18:05:07Z
[ "python", "osx", "unicode", "terminal" ]
Are asynchronous Django model queries possible?
918,298
<p>I'm new to Django, but the application that I have in mind might end up having URLs that look like this:</p> <pre><code>http://mysite/compare/id_1/id_2 </code></pre> <p>Where "id_1" and "id_2" are identifiers of two distinct Model objects. In the handler for "compare" I'd like to asynchronously, and in parallel, query and retrieve objects id_1 and id_2.</p> <p>Is there any way to do this using a standard Django syntax? I'm hoping for pseudocode that ends up looking something like this: </p> <pre><code>import django.async # Issue the model query, but set it up asynchronously. # The next 2 lines don't actually touch my database o1 = Object(id=id_1).async_fetch() o2 = Object(id=id_2).async_fetch() # Now that I know what I want to query, fire off a fetch to do them all # in parallel, and wait for all queries to finish before proceeding. async.Execute((o2,o2)) # Now the code can use data from o1 and o2 below... </code></pre>
18
2009-05-27T22:19:00Z
918,410
<p>There aren't strictly asynchronous operations as you've described, but I think you can achieve the same effect by using django's <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#in-bulk">in_bulk</a> query operator, which takes a list of ids to query.</p> <p>Something like this for the <code>urls.py</code>:</p> <pre><code>urlpatterns = patterns('', (r'^compare/(\d+)/(\d+)/$', 'my.compareview'), ) </code></pre> <p>And this for the view:</p> <pre><code>def compareview(request, id1, id2): # in_bulk returns a dict: { obj_id1: &lt;MyModel instance&gt;, # obj_id2: &lt;MyModel instance&gt; } # the SQL pulls all at once, rather than sequentially... arguably # better than async as it pulls in one DB hit, rather than two # happening at the same time comparables = MyModel.objects.in_bulk([id1, id2]) o1, o2 = (comparables.get(id1), comparables.get(id2)) </code></pre>
11
2009-05-27T23:07:42Z
[ "python", "mysql", "django", "multithreading", "django-models" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,365
<p>You need to run it multiple times to get a real idea of "how fast" each runs. The JVM startup time [for one] is adding to the single running time of the Java version.</p> <p>You're also creating a HashSet with a large initial capacity, which means the backing HashMap will be created with that many available slots, unlike the Python where you create a basic Set. Hard to tell if that would hinder though, as when your HashSet grows it will have to reallocate the stored objects.</p>
2
2009-05-27T22:53:09Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,367
<p>I'm not too familiar with python, but I do know <code>HashSet</code> can't contain primitives, so when you say <code>counts.add(i)</code> the <code>i</code> there is getting autoboxed into a <code>new Integer(i)</code> call. That's probably your problem. </p> <p>If for some reason you really needed a 'set' of integers between 0 and some large n, its probably best declared as an 'boolean[] set = new boolean[n]'. Then you could go through the array and mark items that are in the set as 'true' without incurring the overhead of creating n Integer wrapper objects. If you wanted to go further than that you could use a byte[] of size n/8 and use the individual bits directly. Or perhaps BigInteger. </p> <p>EDIT</p> <p>Stop voting my answer up. Its wrong. </p> <p>EDIT </p> <p>No really, its wrong. I get comparable performance if I do what the question suggest, populate the set with N Integers. if I replace the contents of the for loop with this:</p> <pre><code> Integer[] ints = new Integer[N]; for (int i = 0; i &lt; N; ++i) { ints[i] = i; } </code></pre> <p>Then it only takes 2 seconds. If you don't store the Integer at all then it takes less than 200 millis. Forcing the allocation of 10000000 Integer objects does take some time, but it looks like most of the time is spent inside the HashSet put operation.</p>
3
2009-05-27T22:54:07Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,370
<p>Are you using the -server flag with the jvm? You can't test for performance without it. (You also have to warm up the jvm before doing the test.)</p> <p>Also, you probably want to use <code>TreeSet&lt;Integer&gt;</code>. HashSet will be slower in the long run.</p> <p>And which jvm are you using? The newest I hope.</p> <p><strong>EDIT</strong></p> <p>When I say use TreeSet, I mean in general, not for this benchmark. TreeSet handles the real world issue of non even hashing of objects. If you get too many objects in the same bin in a HashSet, you will perform about O(n).</p>
2
2009-05-27T22:56:58Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,385
<p>I agree with Gandalf about the startup time. Also, you are allocating a huge HashSet which is not at all similar to your python code. I imaging if you put this under a profiler, a good chunk of time would be spent there. Also, inserting new elements is really going to be slow with this size. I would look into TreeSet as suggested.</p>
0
2009-05-27T23:01:27Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,397
<p>It has generally been my experience that python programs run faster than java programs, despite the fact that java is a bit "lower level" language. Incidently, both languages are compiled into byte code (that's what those .pyc file are -- you can think of them as kind of like .class files). Both languages are byte-code interpreted on a virtual stack machine.</p> <p>You would expect python to be slower at things like, for example, <code>a.b</code>. In java, that <code>a.b</code> will resolve into a dereference. Python, on the other hand, has to do one or more hash table lookups: check the local scope, check the module scope, check global scope, check builtins.</p> <p>On the other hand, java is notoriously bad at certain operations such as object creation (which is probably the culprit in your example) and serialization. </p> <p>In summary, there's no simple answer. I wouldn't expect either language to be faster for all code examples.</p> <p><i>Correction: several people have pointed out that java isn't so bad at object creation any more. So, in your example, it's something else. Perhaps it's autoboxing that's expensive, perhaps python's default hashing algorithm is better in this case. In my practical experience, when I rewrite java code to python, I always see a performance increase, but that could be as much due to the language as it is due to rewritng in general leads to performance improvements. </i></p>
7
2009-05-27T23:04:37Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,409
<p>Another possible explanation is that sets in Python are implemented natively in C code, while HashSet's in Java are implemented in Java itself. So, sets in Python should be inherently much faster.</p>
7
2009-05-27T23:06:52Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,432
<p>How much memory did you start the JVM with? It depends? When I run the JVM with your program with 1 Gig of RAM:</p> <pre><code>$ java -Xmx1024M -Xms1024M -classpath . SpeedTest TOTAL TIME = 5.682 10000000 $ python speedtest.py total time = 4.48310899734 10000000 </code></pre> <p>If I run the JVM with less memory, it takes longer ... considerably longer:</p> <pre><code>$ java -Xmx768M -Xms768M -classpath . SpeedTest TOTAL TIME = 6.706 10000000 $ java -Xmx600M -Xms600M -classpath . SpeedTest TOTAL TIME = 14.086 10000000 </code></pre> <p>I think the <code>HashSet</code> is the performance bottleneck in this particular instance. If I replace the <code>HashSet</code> with a <code>LinkedList</code>, the program gets substantially faster.</p> <p>Finally -- note that Java programs are initially interpreted and only those methods that are called many times are compiled. Thus, you're probably comparing Python to Java's interpreter, not the compiler.</p>
1
2009-05-27T23:14:12Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,455
<p>I find benchmarks like this to be meaningless. I don't solve problems that look like the test case. It's not terribly interesting.</p> <p>I'd much rather see a solution for a meaningful linear algebra solution using NumPy and JAMA. Maybe I'll try it and report back with results.</p>
4
2009-05-27T23:20:36Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,456
<p>There's a number of issues here which I'd like to bring together.</p> <p>First if it's a program that you are only going to run once, does it matter it takes an extra few seconds?</p> <p>Secondly, this is just one microbenchmarks. Microbenchmarks are pointless for comparing performance.</p> <p>Startup has a number of issues.</p> <p>The Java runtime is much bigger than Python so takes longer to load from disk and takes up more memory which may be important if you are swapping.</p> <p>If you haven't set <code>-Xms</code> you may be running the GC only to resize the heap. Might as well have the heap properly sized at the start.</p> <p>It is true that Java starts off interpreting and then compiles. Around 1,500 iterations for Sun client [C1] Hotspot and 10,000 for server [C2]. Server Hotspot will give you better performance eventually, but take more memory. We may see client Hotspot use server for very frequently executed code for best of both worlds. However, this should not usually be a question of seconds.</p> <p><strong>Most importantly you may be creating two objects per iteration. For most code, you wouldn't be creating these tiny objects for such a proportion of the execution. TreeSet may be better on number of objects score, with 6u14 and Harmony getting even better.</strong></p> <p>Python may possibly be winning by storing small integer objects in references instead of actually have an object. That is undoubtably a good optimisation.</p> <p>A problem with a lot of benchmarks is you are mixing a lot of different code up in one method. You wouldn't write code you cared about like that, would you? So why are you attempting to performance test which is unlike code you would actually like to run fast?</p> <p>Better data structure: Something like <code>BitSet</code> would seem to make sense (although that has ynchronisation on it, which may or may not impact performance).</p>
3
2009-05-27T23:21:41Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,467
<p>The biggest issue is probably that what the given code measures is <a href="http://en.wikipedia.org/wiki/Wall%5Ftime" rel="nofollow">wall time</a> -- what your watch measures -- but what should be measured to compare code runtime is <a href="http://en.wikipedia.org/wiki/Process%5Ftime" rel="nofollow">process time</a> -- the amount of time the cpu spend executing that particular code and not other tasks.</p>
0
2009-05-27T23:24:43Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,501
<p><strong>Edit: A TreeSet might be faster for the real use case, depending on allocation patterns. My comments below deals only with this simplified scenario. However, I do not believe that it would make a very significant difference. The real issue lays elsewhere.</strong> </p> <p>Several people here has recommended replacing the HashSet with a TreeSet. This sounds like a very strange advice to me, since there's no way that a data structure with O(log n) insertion time is faster then a O(1) structure that preallocates enough buckets to store all the elements.</p> <p>Here's some code to benchmark this:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; Set counts; System.out.println("HashSet:"); counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); counts.clear(); System.out.println("TreeSet:"); counts = new TreeSet(); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>And here's the result on my machine:</p> <pre><code>$ java -Xmx1024M SpeedTest HashSet: TOTAL TIME = 4.436 10000000 TreeSet: TOTAL TIME = 8.163 10000000 </code></pre> <p>Several people also argued that boxing isn't a performance issue and that object creation is inexpensive. While it's true that object creation is fast, it's definitely not as fast as primitives:</p> <pre><code>import java.util.*; class SpeedTest2 { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; System.out.println("primitives:"); startTime = System.currentTimeMillis(); int[] primitive = new int[iterations]; for (int i = 0; i &lt; iterations; i++) { primitive[i] = i; } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println("primitives:"); startTime = System.currentTimeMillis(); Integer[] boxed = new Integer[iterations]; for (int i = 0; i &lt; iterations; i++) { boxed[i] = i; } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); } } </code></pre> <p>Result:</p> <pre><code>$ java -Xmx1024M SpeedTest2 primitives: TOTAL TIME = 0.058 primitives: TOTAL TIME = 1.402 </code></pre> <p>Moreover, creating a lot of objects results in additional overhead from the garbage collector. This becomes significant when you start keeping tens of millions of live objects in memory.</p>
5
2009-05-27T23:33:12Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,572
<p>You can make the Java microbenchamrk much faster, by <strong>adding</strong> just a simple little extra.</p> <pre><code> HashSet counts = new HashSet((2*iterations), 0.75f); </code></pre> <p>becomes</p> <pre><code> HashSet counts = new HashSet((2*iterations), 0.75f) { @Override public boolean add(Object element) { return false; } }; </code></pre> <p>Simple, faster and gets the same result.</p>
0
2009-05-27T23:59:54Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,861
<p>Just a stab in the dark here, but some optimizations that Python is making that Java probably isn't:</p> <ul> <li>The range() call in Python is creating all 10000000 integer objects at once, in optimized C code. Java must create an Integer object each iteration, which may be slower. </li> <li>In Python, ints are immutable, so you can just store a reference to a global "42", for example, rather than allocating a slot for the object. I'm not sure how Java boxed Integer objects compare.</li> <li>Many of the built-in Python algorithms and data structures are rather heavily optimized for special cases. For instance, the hash function for integers is, simply the identity function. If Java is using a more "clever" hash function, this could slow things down quite a bit. If most of your time is spent in data structure code, I wouldn't be surprised at all to see Python beat Java given the amount of effort that has been spent over the years hand-tuning the Python C implementation.</li> </ul>
1
2009-05-28T01:53:24Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
918,874
<p>You might want to see if you can "prime" the JIT compiler into compiling the section of code you're interested in, by perhaps running it as a function once beforehand and sleeping briefly afterwords. This might allow the JVM to compile the function down to native code.</p>
0
2009-05-28T01:59:17Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
919,844
<p>I suspect that is that Python uses the integer value itself as its hash and the hashtable based implementation of set uses that value directly. From the comments in the <a href="http://svn.python.org/view/python/trunk/Objects/dictobject.c?revision=72958&amp;view=markup" rel="nofollow">source</a>:</p> <blockquote> <p>This isn't necessarily bad! To the contrary, in a table of size 2**i, taking the low-order i bits as the initial table index is extremely fast, and there are no collisions at all for dicts indexed by a contiguous range of ints. The same is approximately true when keys are "consecutive" strings. So this gives better-than-random behavior in common cases, and that's very desirable.</p> </blockquote> <p>This microbenchmark is somewhat of a best case for Python because it results in exactly zero hash collisions. Whereas, if Javas HashSet is rehashing the keys it has to perform the additional work and also gets much worse behavior with collisions.</p> <p>If you store the range(iterations) in a temporary variable and do a random.shuffle on it before the loop the runtime is more than 2x slower even if the shuffle and list creation is done outside the loop.</p>
12
2009-05-28T08:46:54Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
919,966
<p>You're not really testing Java vs. Python, you're testing <code>java.util.HashSet</code> using autoboxed Integers vs. Python's native set and integer handling.</p> <p>Apparently, the Python side in this particular microbenchmark is indeed faster.</p> <p>I tried replacing HashSet with <code>TIntHashSet</code> from <a href="http://trove4j.sourceforge.net/">GNU trove</a> and achieved a speedup factor between 3 and 4, bringing Java slightly ahead of Python.</p> <p>The real question is whether your example code is really as representative of your application code as you think. Have you run a profiler and determined that most of the CPU time is spent in putting a huge number of ints into a HashSet? If not, the example is irrelevant. Even if the only difference is that your production code stores other objects than ints, their creation and the computation of their hashcode could easily dominate the set insertion (and totally destroy Python's advantage in handling ints specially), making this whole question pointless.</p>
20
2009-05-28T09:26:11Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
919,980
<p>If you really want to store primitive types in a set, and do heavy work on it, roll your own set in Java. The generic classes are not fast enough for scientific computing.</p> <p>As Ants Aasma mentions, Python bypasses hashing and uses the integer directly. Java creates an Integer object (<a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html" rel="nofollow">autoboxing</a>), and then casts it to an Object (in your implementation). This object must be hashed, as well, for use in a hash set.</p> <p>For a fun comparision, try this:</p> <p><strong>Java</strong></p> <pre><code>import java.util.HashSet; class SpeedTest { public static class Element { private int m_i; public Element(int i) { m_i = i; } } public static void main(String[] args) { long startTime; long totalTime; int iterations = 1000000; HashSet&lt;Element&gt; counts = new HashSet&lt;Element&gt;((int)(2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; ++i) { counts.add(new Element(i)); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>Results:</p> <pre><code>$java SpeedTest TOTAL TIME = 3.028 1000000 $java -Xmx1G -Xms1G SpeedTest TOTAL TIME = 0.578 1000000 </code></pre> <p><strong>Python</strong></p> <pre><code>#!/usr/bin/python import time import sys class Element(object): def __init__(self, i): self.num = i def main(args): iterations = 1000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(Element(i)) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>Results:</p> <pre><code>$./speedtest.py total time = 20.6943161488 1000000 </code></pre> <p>How's that for 'python is faster than java'?</p>
2
2009-05-28T09:30:18Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
920,067
<p>I'd like to dispel a couple myths I saw in the answers:</p> <p>Java is compiled, yes, to bytecode but ultimately to native code in most runtime environments. People who say C is inherently faster aren't telling the entire story, I could make a case that byte compiled languages are inherently faster because the JIT compiler can make machine-specific optimizations that are unavailable to way-ahead-of-time compilers.</p> <p>A number of things that could make the differences are:</p> <ul> <li>Python's hash tables and sets are the most heavily optimized objects in Python, and Python's hash function is designed to return similar results for similar inputs: hashing an integer just returns the integer, guaranteeing that you will NEVER see a collision in a hash table of consecutive integers in Python.</li> <li>A secondary effect of the above is that the Python code will have high locality of reference as you'll be accessing the hash table in sequence. </li> <li>Java does some fancy boxing and unboxing of integers when you add them to collections. On the bonus side, this makes arithmetic way faster in Java than Python (as long as you stay away from bignums) but on the downside it means more allocations than you're used to.</li> </ul>
6
2009-05-28T09:53:03Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
939,697
<p>A few changes for faster Python. </p> <pre><code>#!/usr/bin/python import time import sys import psyco #&lt;&lt;&lt;&lt; psyco.full() class Element(object): __slots__=["num"] #&lt;&lt;&lt;&lt; def __init__(self, i): self.num = i def main(args): iterations = 1000000 counts = set() startTime = time.time(); for i in xrange(0, iterations): counts.add(Element(i)) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>Before</p> <pre><code>(env)~$ python speedTest.py total time = 8.82906794548 1000000 </code></pre> <p>After</p> <pre><code>(env)~$ python speedTest.py total time = 2.44039201736 1000000 </code></pre> <p>Now some good old cheating and ...</p> <pre><code>#!/usr/bin/python import time import sys import psyco psyco.full() class Element(object): __slots__=["num"] def __init__(self, i): self.num = i def main(args): iterations = 1000000 counts = set() elements = [Element(i) for i in range(0, iterations)] startTime = time.time(); for e in elements: counts.add(e) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) (env)~$ python speedTest.py total time = 0.526521921158 1000000 </code></pre>
1
2009-06-02T13:53:25Z
[ "java", "python", "microbenchmark" ]
My python program executes faster than my java version of the same program. What gives?
918,359
<p><strong>Update: 2009-05-29</strong></p> <p>Thanks for all the suggestions and advice. <strong>I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.</strong> In the end I was able to make the java code the fastest.</p> <p>Lessons:</p> <ul> <li><p>My example code below shows the insertion of primitive ints but the production code is actually storing strings (my bad). When I corrected that the python execution time went from 2.8 seconds to 9.6. So right off the bat, the java was actually faster when storing objects. </p></li> <li><p>But it doesn't stop there. I had been executing the java program as follows:</p> <p>java -Xmx1024m SpeedTest</p></li> </ul> <p>But if you set the initial heap size as follows you get a huge improvement:</p> <pre><code>java -Xms1024m -Xmx1024m SpeedTest </code></pre> <p>This simple change reduced the execution time by more than 50%. So the final result for my SpeedTest is python 9.6 seconds. Java 6.5 seconds. </p> <p><strong>Original Question:</strong></p> <p>I had the following python code:</p> <pre><code>import time import sys def main(args): iterations = 10000000 counts = set() startTime = time.time(); for i in range(0, iterations): counts.add(i) totalTime = time.time() - startTime print 'total time =',totalTime print len(counts) if __name__ == "__main__": main(sys.argv) </code></pre> <p>And it executed in about 3.3 seconds on my machine but I wanted to make it faster so I decided to program it in java. I assumed that because java is compiled and is generally considered to be faster than python I would see some big paybacks.</p> <p>Here is the java code:</p> <pre><code>import java.util.*; class SpeedTest { public static void main(String[] args) { long startTime; long totalTime; int iterations = 10000000; HashSet counts = new HashSet((2*iterations), 0.75f); startTime = System.currentTimeMillis(); for(int i=0; i&lt;iterations; i++) { counts.add(i); } totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(counts.size()); } } </code></pre> <p>So this java code does basically the same thing as the python code. But it executed in 8.3 seconds instead of 3.3. </p> <p>I have extracted this simple example from a real-world example to simplify things. The critical element is that I have (set or hashSet) that ends up with a lot of members much like the example.</p> <p>Here are my questions:</p> <ol> <li><p>How come my python implementation is faster than my java implementation?</p></li> <li><p>Is there a better data structure to use than the hashSet (java) to hold a unique collection?</p></li> <li><p>What would make the python implementation faster?</p></li> <li><p>What would make the java implementation faster?</p></li> </ol> <p>UPDATE:</p> <p>Thanks to all who have contributed so far. Please allow me to add some details.</p> <p>I have not included my production code because it is quite complex. And would generate a lot of distraction. The case I present above is the most simplified possible. By that I mean that the java put call seems to be much slower than the python set`s add(). </p> <p>The java implementation of the production code is also about 2.5 - 3 times slower than the python version -- just like the above. </p> <p>I am not concerned about vm warmup or startup overhead. I just want to compare the code from my startTime to my totalTime. Please do not concern yourselves with other matters. </p> <p>I initialized the hashset with more than enough buckets so that it should never have to rehash. (I will always know ahead of time how many elements the collection will ultimately contain.) I suppose one could argue that I should have initialized it to iterations/0.75. But if you try it you will see that execution time is not significantly impacted.</p> <p>I set Xmx1024m for those that were curious (my machine has 4GB of ram). </p> <p>I am using java version: Java(TM) SE Runtime Environment (build 1.6.0_13-b03).</p> <p>In the production version of I am storing a string (2-15 chars) in the hashSet so I cannot use primitives, although that is an interesting case.</p> <p>I have run the code many, many times. I have very high confidence that the python code is between 2.5 and 3 times faster than the java code.</p>
15
2009-05-27T22:48:42Z
1,773,936
<p>Well, if you're going to tune the Java program, you might as well tune the Python program too.</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.Timer('x = set()\nfor i in range(10000000):\n x.add(i)').repeat(3, 1) [2.1174559593200684, 2.0019571781158447, 1.9973630905151367] &gt;&gt;&gt; timeit.Timer('x = set()\nfor i in xrange(10000000):\n x.add(i)').repeat(3, 1) [1.8742368221282959, 1.8714439868927002, 1.869229793548584] &gt;&gt;&gt; timeit.Timer('x = set(xrange(10000000))').repeat(3, 1) [0.74582195281982422, 0.73061800003051758, 0.73396801948547363] </code></pre> <p>Just using <code>xrange</code> makes it about 8% faster on my machine. And the expression <code>set(xrange(10000000))</code> builds exactly the same set, but <strong>2.5x faster</strong> (from 1.87 seconds to 0.74).</p> <p>I like how tuning a Python program makes it shorter. :) But Java can do the same trick. As everyone knows, if you want a dense set of smallish integers in Java, you don't use a hash table. You use a <code>java.util.BitSet</code>!</p> <pre><code>BitSet bits = new BitSet(iterations); startTime = System.currentTimeMillis(); bits.set(0, iterations, true); totalTime = System.currentTimeMillis() - startTime; System.out.println("TOTAL TIME = "+( totalTime/1000f) ); System.out.println(bits.cardinality()); </code></pre> <p>That should be fairly quick. Unfortunately I don't have the time to test it right now.</p>
0
2009-11-20T23:53:31Z
[ "java", "python", "microbenchmark" ]
Is there a better way than int( byte_buffer.encode('hex'), 16 )
918,754
<p>In Python, I'm constantly using the following sequence to get an integer value from a byte buffer (in python this is a str).</p> <p>I'm getting the buffer from the struct.unpack() routine. When I unpack a 'char' using</p> <pre><code>byte_buffer, = struct.unpack('c', raw_buffer) int_value = int( byte_buffer.encode('hex'), 16 ) </code></pre> <p>Is there a better way? </p>
3
2009-05-28T01:16:47Z
918,774
<p>The <a href="http://docs.python.org/library/struct" rel="nofollow">struct</a> module is good at unpacking binary data.</p> <pre><code>int_value = struct.unpack('&gt;I', byte_buffer)[0] </code></pre>
5
2009-05-28T01:21:52Z
[ "python", "integer", "types", "byte" ]
Is there a better way than int( byte_buffer.encode('hex'), 16 )
918,754
<p>In Python, I'm constantly using the following sequence to get an integer value from a byte buffer (in python this is a str).</p> <p>I'm getting the buffer from the struct.unpack() routine. When I unpack a 'char' using</p> <pre><code>byte_buffer, = struct.unpack('c', raw_buffer) int_value = int( byte_buffer.encode('hex'), 16 ) </code></pre> <p>Is there a better way? </p>
3
2009-05-28T01:16:47Z
918,960
<blockquote> <p>Bounded to 1 byte – Noah Campbell 18 mins ago</p> </blockquote> <p>The best way to do this then is to instantiate a struct unpacker.</p> <pre><code>from struct import Struct unpacker = Struct("b") unpacker.unpack("z")[0] </code></pre> <p>Note that you can change "b" to "B" if you want an unsigned byte. Also, endian format is not needed.</p> <p>For anyone else who wants to know a method for unbounded integers, create a question, and tell me in the comments.</p>
2
2009-05-28T02:36:26Z
[ "python", "integer", "types", "byte" ]
Is there a better way than int( byte_buffer.encode('hex'), 16 )
918,754
<p>In Python, I'm constantly using the following sequence to get an integer value from a byte buffer (in python this is a str).</p> <p>I'm getting the buffer from the struct.unpack() routine. When I unpack a 'char' using</p> <pre><code>byte_buffer, = struct.unpack('c', raw_buffer) int_value = int( byte_buffer.encode('hex'), 16 ) </code></pre> <p>Is there a better way? </p>
3
2009-05-28T01:16:47Z
923,041
<p>If we're talking about getting the integer value of a byte, then you want this:</p> <pre><code>ord(byte_buffer) </code></pre> <p>Can't understand why it isn't already suggested.</p>
1
2009-05-28T20:40:11Z
[ "python", "integer", "types", "byte" ]
Case insensitive replace
919,056
<p>What's the easiest way to do a case-insensitive string replacement in Python?</p>
74
2009-05-28T03:35:24Z
919,067
<p>The <code>string</code> type doesn't support this. You're probably best off using <a href="http://docs.python.org/library/re.html#re.RegexObject.sub">the regular expression sub method</a> with the <a href="http://docs.python.org/library/re.html#re.IGNORECASE">re.IGNORECASE</a> option.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; insensitive_hippo = re.compile(re.escape('hippo'), re.IGNORECASE) &gt;&gt;&gt; insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday') 'I want a giraffe for my birthday' </code></pre>
104
2009-05-28T03:39:13Z
[ "python", "string", "case-insensitive" ]
Case insensitive replace
919,056
<p>What's the easiest way to do a case-insensitive string replacement in Python?</p>
74
2009-05-28T03:35:24Z
919,074
<pre><code>import re pattern = re.compile("hello", re.IGNORECASE) pattern.sub("bye", "hello HeLLo HELLO") # 'bye bye bye' </code></pre>
56
2009-05-28T03:41:04Z
[ "python", "string", "case-insensitive" ]
Case insensitive replace
919,056
<p>What's the easiest way to do a case-insensitive string replacement in Python?</p>
74
2009-05-28T03:35:24Z
4,759,732
<p>This doesn't require RegularExp</p> <pre><code>def ireplace(old, new, text): """ Replace case insensitive Raises ValueError if string not found """ index_l = text.lower().index(old.lower()) return text[:index_l] + new + text[index_l + len(old):] </code></pre>
1
2011-01-21T14:09:54Z
[ "python", "string", "case-insensitive" ]
Case insensitive replace
919,056
<p>What's the easiest way to do a case-insensitive string replacement in Python?</p>
74
2009-05-28T03:35:24Z
4,773,614
<p>Continuing on bFloch's answer, this function will change not one, but all occurrences of old with new - in a case insensitive fashion. </p> <pre><code>def ireplace(old, new, text): idx = 0 while idx &lt; len(text): index_l = text.lower().find(old.lower(), idx) if index_l == -1: return text text = text[:index_l] + new + text[index_l + len(old):] idx = index_l + len(old) return text </code></pre>
4
2011-01-23T11:46:46Z
[ "python", "string", "case-insensitive" ]
Case insensitive replace
919,056
<p>What's the easiest way to do a case-insensitive string replacement in Python?</p>
74
2009-05-28T03:35:24Z
9,312,577
<p>never posted an answer before and this thread is really old but i came up with another sollution and figured i could get your respons, Im not seasoned in Python programming so if there are appearant drawbacks to it, please point them out since its good learning :)</p> <pre><code>i='I want a hIPpo for my birthday' key='hippo' swp='giraffe' o=(i.lower().split(key)) c=0 p=0 for w in o: o[c]=i[p:p+len(w)] p=p+len(key+w) c+=1 print(swp.join(o)) </code></pre>
-2
2012-02-16T13:59:28Z
[ "python", "string", "case-insensitive" ]
Case insensitive replace
919,056
<p>What's the easiest way to do a case-insensitive string replacement in Python?</p>
74
2009-05-28T03:35:24Z
9,709,563
<p>Very simple, in a single line:</p> <pre><code>import re re.sub("(?i)hello","bye", "hello HeLLo HELLO") #'bye bye bye' re.sub("(?i)he\.llo","bye", "he.llo He.LLo HE.LLO") #'bye bye bye' </code></pre> <p>Or, use the optional "flags" argument:</p> <pre><code>import re re.sub("hello", "bye", "hello HeLLo HELLO", flags=re.I) #'bye bye bye' re.sub("he\.llo", "bye", "he.llo He.LLo HE.LLO", flags=re.I) #'bye bye bye' </code></pre>
16
2012-03-14T20:14:03Z
[ "python", "string", "case-insensitive" ]
Case insensitive replace
919,056
<p>What's the easiest way to do a case-insensitive string replacement in Python?</p>
74
2009-05-28T03:35:24Z
15,831,118
<p>Like Blair Conrad says string.replace doesn't support this.</p> <p>Use the regex <code>re.sub</code>, but remember to escape the replacement string first. Note that there's no flags-option in 2.6 for <code>re.sub</code>, so you'll have to use the embedded modifier <code>'(?i)'</code> (or a RE-object, see Blair Conrad's answer). Also, another pitfall is that sub will process backslash escapes in the replacement text, if a string is given. To avoid this one can instead pass in a lambda.</p> <p>Here's a function:</p> <pre><code>import re def ireplace(old, repl, text): return re.sub('(?i)'+re.escape(old), lambda m: repl, text) &gt;&gt;&gt; ireplace('hippo?', 'giraffe!?', 'You want a hiPPO?') 'You want a giraffe!?' &gt;&gt;&gt; ireplace(r'[binfolder]', r'C:\Temp\bin', r'[BinFolder]\test.exe') 'C:\\Temp\\bin\\test.exe' </code></pre>
1
2013-04-05T10:03:57Z
[ "python", "string", "case-insensitive" ]
Case insensitive replace
919,056
<p>What's the easiest way to do a case-insensitive string replacement in Python?</p>
74
2009-05-28T03:35:24Z
26,600,348
<p>I was having \t being converted to the <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literals" rel="nofollow">escape sequences</a> (scroll a bit down), so I noted that <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow">re.sub</a> converts backslashed escaped characters to escape sequences.</p> <p>To prevent that I wrote the following:</p> <p>Replace case insensitive.</p> <pre><code>import re def ireplace(findtxt, replacetxt, data): return replacetxt.join( re.compile(findtxt, flags=re.I).split(data) ) </code></pre> <p>Also, if you want it to replace with the escape characters, like the other answers here that are getting the special meaning bashslash characters converted to escape sequences, just decode your find and, or replace string. In Python 3, might have to do something like .decode("unicode_escape") # python3</p> <pre><code>findtxt = findtxt.decode('string_escape') # python2 replacetxt = replacetxt.decode('string_escape') # python2 data = ireplace(findtxt, replacetxt, data) </code></pre> <p>Tested in Python 2.7.8</p> <p>Hope that helps.</p>
0
2014-10-28T03:18:39Z
[ "python", "string", "case-insensitive" ]
Are there memory efficiencies gained when code is wrapped in functions?
919,103
<p>I have been working on some code. My usual approach is to first solve all of the pieces of the problem, creating the loops and other pieces of code I need as I work through the problem and then if I expect to reuse the code I go back through it and group the parts of code together that I think should be grouped to create functions. </p> <p>I have just noticed that creating functions and calling them seems to be much more efficient than writing lines of code and deleting containers as I am finished with them. </p> <p>for example:</p> <pre><code>def someFunction(aList): do things to aList that create a dictionary return aDict </code></pre> <p>seems to release more memory at the end than</p> <pre><code>&gt;&gt;do things to alist &gt;&gt;that create a dictionary &gt;&gt;del(aList) </code></pre> <p>Is this expected behavior? </p> <p>EDIT added example code</p> <p>When this function finishes running the PF Usage shows an increase of about 100 mb the filingsList has about 8 million lines.</p> <pre><code>def getAllCIKS(filingList): cikDICT=defaultdict(int) for filing in filingList: if filing.startswith('.'): del(filing) continue cik=filing.split('^')[0].strip() cikDICT[cik]+=1 del(filing) ciklist=cikDICT.keys() ciklist.sort() return ciklist allCIKS=getAllCIKS(open(r'c:\filinglist.txt').readlines()) </code></pre> <p>If I run this instead I show an increase of almost 400 mb</p> <pre><code>cikDICT=defaultdict(int) for filing in open(r'c:\filinglist.txt').readlines(): if filing.startswith('.'): del(filing) continue cik=filing.split('^')[0].strip() cikDICT[cik]+=1 del(filing) ciklist=cikDICT.keys() ciklist.sort() del(cikDICT) </code></pre> <p>EDIT I have been playing around with this some more today. My observation and question should be refined a bit since my focus has been on the PF Usage. Unfortunately I can only poke at this between my other tasks. However I am starting to wonder about references versus copies. If I create a dictionary from a list does the dictionary container hold a copy of the values that came from the list or do they hold references to the values in the list? My bet is that the values are copied instead of referenced. </p> <p>Another thing I noticed is that items in the GC list were items from containers that were deleted. Does that make sense? Soo I have a list and suppose each of the items in the list was [(aTuple),anInteger,[another list]]. When I started learning about how to manipulate the gc objects and inspect them I found those objects in the gc even though the list had been forcefully deleted and even though I passed the 0,1 &amp; 2 value to the method that I don't remember to try to still delete them. </p> <p>I appreciate the insights people have been sharing. Unfortunately I am always interested in figuring out how things work under the hood. </p>
3
2009-05-28T03:52:02Z
919,108
<p>Some extra memory is freed when you return from a function, but that's exactly as much extra memory as was allocated to call the function in the first place. In any case - if you seeing a large amount of difference, that's likely an artifact of the state of the runtime, and is not something you should really be worrying about. If you are running low on memory, the way to solve the problem is to keep more data on disk using things like b-trees (or just use a database), or use algorithms that use less memory. Also, keep an eye out for making unnecessary copies of large data structures.</p> <p>The real memory savings in creating functions is in your short-term memory. By moving something into a function, you reduce the amount of detail you need to remember by encapsulating part of the minutia away.</p>
0
2009-05-28T03:54:34Z
[ "python", "memory-management", "function" ]
Are there memory efficiencies gained when code is wrapped in functions?
919,103
<p>I have been working on some code. My usual approach is to first solve all of the pieces of the problem, creating the loops and other pieces of code I need as I work through the problem and then if I expect to reuse the code I go back through it and group the parts of code together that I think should be grouped to create functions. </p> <p>I have just noticed that creating functions and calling them seems to be much more efficient than writing lines of code and deleting containers as I am finished with them. </p> <p>for example:</p> <pre><code>def someFunction(aList): do things to aList that create a dictionary return aDict </code></pre> <p>seems to release more memory at the end than</p> <pre><code>&gt;&gt;do things to alist &gt;&gt;that create a dictionary &gt;&gt;del(aList) </code></pre> <p>Is this expected behavior? </p> <p>EDIT added example code</p> <p>When this function finishes running the PF Usage shows an increase of about 100 mb the filingsList has about 8 million lines.</p> <pre><code>def getAllCIKS(filingList): cikDICT=defaultdict(int) for filing in filingList: if filing.startswith('.'): del(filing) continue cik=filing.split('^')[0].strip() cikDICT[cik]+=1 del(filing) ciklist=cikDICT.keys() ciklist.sort() return ciklist allCIKS=getAllCIKS(open(r'c:\filinglist.txt').readlines()) </code></pre> <p>If I run this instead I show an increase of almost 400 mb</p> <pre><code>cikDICT=defaultdict(int) for filing in open(r'c:\filinglist.txt').readlines(): if filing.startswith('.'): del(filing) continue cik=filing.split('^')[0].strip() cikDICT[cik]+=1 del(filing) ciklist=cikDICT.keys() ciklist.sort() del(cikDICT) </code></pre> <p>EDIT I have been playing around with this some more today. My observation and question should be refined a bit since my focus has been on the PF Usage. Unfortunately I can only poke at this between my other tasks. However I am starting to wonder about references versus copies. If I create a dictionary from a list does the dictionary container hold a copy of the values that came from the list or do they hold references to the values in the list? My bet is that the values are copied instead of referenced. </p> <p>Another thing I noticed is that items in the GC list were items from containers that were deleted. Does that make sense? Soo I have a list and suppose each of the items in the list was [(aTuple),anInteger,[another list]]. When I started learning about how to manipulate the gc objects and inspect them I found those objects in the gc even though the list had been forcefully deleted and even though I passed the 0,1 &amp; 2 value to the method that I don't remember to try to still delete them. </p> <p>I appreciate the insights people have been sharing. Unfortunately I am always interested in figuring out how things work under the hood. </p>
3
2009-05-28T03:52:02Z
919,134
<p>You can use the <a href="http://docs.python.org/library/gc.html" rel="nofollow">Python garbage collector interface</a> provided to more closely examine what (if anything) is being left around in the second case. Specifically, you may want to check out <a href="http://docs.python.org/library/gc.html#gc.get%5Fobjects" rel="nofollow">gc.get_objects()</a> to see what is left uncollected, or <a href="http://docs.python.org/library/gc.html#gc.garbage" rel="nofollow">gc.garbage</a> to see if you have any reference cycles.</p>
1
2009-05-28T04:08:41Z
[ "python", "memory-management", "function" ]
Are there memory efficiencies gained when code is wrapped in functions?
919,103
<p>I have been working on some code. My usual approach is to first solve all of the pieces of the problem, creating the loops and other pieces of code I need as I work through the problem and then if I expect to reuse the code I go back through it and group the parts of code together that I think should be grouped to create functions. </p> <p>I have just noticed that creating functions and calling them seems to be much more efficient than writing lines of code and deleting containers as I am finished with them. </p> <p>for example:</p> <pre><code>def someFunction(aList): do things to aList that create a dictionary return aDict </code></pre> <p>seems to release more memory at the end than</p> <pre><code>&gt;&gt;do things to alist &gt;&gt;that create a dictionary &gt;&gt;del(aList) </code></pre> <p>Is this expected behavior? </p> <p>EDIT added example code</p> <p>When this function finishes running the PF Usage shows an increase of about 100 mb the filingsList has about 8 million lines.</p> <pre><code>def getAllCIKS(filingList): cikDICT=defaultdict(int) for filing in filingList: if filing.startswith('.'): del(filing) continue cik=filing.split('^')[0].strip() cikDICT[cik]+=1 del(filing) ciklist=cikDICT.keys() ciklist.sort() return ciklist allCIKS=getAllCIKS(open(r'c:\filinglist.txt').readlines()) </code></pre> <p>If I run this instead I show an increase of almost 400 mb</p> <pre><code>cikDICT=defaultdict(int) for filing in open(r'c:\filinglist.txt').readlines(): if filing.startswith('.'): del(filing) continue cik=filing.split('^')[0].strip() cikDICT[cik]+=1 del(filing) ciklist=cikDICT.keys() ciklist.sort() del(cikDICT) </code></pre> <p>EDIT I have been playing around with this some more today. My observation and question should be refined a bit since my focus has been on the PF Usage. Unfortunately I can only poke at this between my other tasks. However I am starting to wonder about references versus copies. If I create a dictionary from a list does the dictionary container hold a copy of the values that came from the list or do they hold references to the values in the list? My bet is that the values are copied instead of referenced. </p> <p>Another thing I noticed is that items in the GC list were items from containers that were deleted. Does that make sense? Soo I have a list and suppose each of the items in the list was [(aTuple),anInteger,[another list]]. When I started learning about how to manipulate the gc objects and inspect them I found those objects in the gc even though the list had been forcefully deleted and even though I passed the 0,1 &amp; 2 value to the method that I don't remember to try to still delete them. </p> <p>I appreciate the insights people have been sharing. Unfortunately I am always interested in figuring out how things work under the hood. </p>
3
2009-05-28T03:52:02Z
919,172
<p>Maybe you used some local variables in your function, which are implicitly released by reference counting at the end of the function, while they are not released at the end of your code segment?</p>
3
2009-05-28T04:22:40Z
[ "python", "memory-management", "function" ]
Are there memory efficiencies gained when code is wrapped in functions?
919,103
<p>I have been working on some code. My usual approach is to first solve all of the pieces of the problem, creating the loops and other pieces of code I need as I work through the problem and then if I expect to reuse the code I go back through it and group the parts of code together that I think should be grouped to create functions. </p> <p>I have just noticed that creating functions and calling them seems to be much more efficient than writing lines of code and deleting containers as I am finished with them. </p> <p>for example:</p> <pre><code>def someFunction(aList): do things to aList that create a dictionary return aDict </code></pre> <p>seems to release more memory at the end than</p> <pre><code>&gt;&gt;do things to alist &gt;&gt;that create a dictionary &gt;&gt;del(aList) </code></pre> <p>Is this expected behavior? </p> <p>EDIT added example code</p> <p>When this function finishes running the PF Usage shows an increase of about 100 mb the filingsList has about 8 million lines.</p> <pre><code>def getAllCIKS(filingList): cikDICT=defaultdict(int) for filing in filingList: if filing.startswith('.'): del(filing) continue cik=filing.split('^')[0].strip() cikDICT[cik]+=1 del(filing) ciklist=cikDICT.keys() ciklist.sort() return ciklist allCIKS=getAllCIKS(open(r'c:\filinglist.txt').readlines()) </code></pre> <p>If I run this instead I show an increase of almost 400 mb</p> <pre><code>cikDICT=defaultdict(int) for filing in open(r'c:\filinglist.txt').readlines(): if filing.startswith('.'): del(filing) continue cik=filing.split('^')[0].strip() cikDICT[cik]+=1 del(filing) ciklist=cikDICT.keys() ciklist.sort() del(cikDICT) </code></pre> <p>EDIT I have been playing around with this some more today. My observation and question should be refined a bit since my focus has been on the PF Usage. Unfortunately I can only poke at this between my other tasks. However I am starting to wonder about references versus copies. If I create a dictionary from a list does the dictionary container hold a copy of the values that came from the list or do they hold references to the values in the list? My bet is that the values are copied instead of referenced. </p> <p>Another thing I noticed is that items in the GC list were items from containers that were deleted. Does that make sense? Soo I have a list and suppose each of the items in the list was [(aTuple),anInteger,[another list]]. When I started learning about how to manipulate the gc objects and inspect them I found those objects in the gc even though the list had been forcefully deleted and even though I passed the 0,1 &amp; 2 value to the method that I don't remember to try to still delete them. </p> <p>I appreciate the insights people have been sharing. Unfortunately I am always interested in figuring out how things work under the hood. </p>
3
2009-05-28T03:52:02Z
920,679
<p>Maybe you should re-engineer your code to get rid of unnecessary variables (that may not be freed instantly)... how about the following snippet?</p> <pre><code>myfile = file(r"c:\fillinglist.txt") ciklist = sorted(set(x.split("^")[0].strip() for x in myfile if not x.startswith("."))) </code></pre> <p>EDIT: I don't know why this answer was voted negative... Maybe because it's short? Or maybe because the dude who voted was unable to understand how this one-liner does the same that the code in the question without creating unnecessary temporal containers?</p> <p>Sigh...</p>
0
2009-05-28T12:53:26Z
[ "python", "memory-management", "function" ]
Are there memory efficiencies gained when code is wrapped in functions?
919,103
<p>I have been working on some code. My usual approach is to first solve all of the pieces of the problem, creating the loops and other pieces of code I need as I work through the problem and then if I expect to reuse the code I go back through it and group the parts of code together that I think should be grouped to create functions. </p> <p>I have just noticed that creating functions and calling them seems to be much more efficient than writing lines of code and deleting containers as I am finished with them. </p> <p>for example:</p> <pre><code>def someFunction(aList): do things to aList that create a dictionary return aDict </code></pre> <p>seems to release more memory at the end than</p> <pre><code>&gt;&gt;do things to alist &gt;&gt;that create a dictionary &gt;&gt;del(aList) </code></pre> <p>Is this expected behavior? </p> <p>EDIT added example code</p> <p>When this function finishes running the PF Usage shows an increase of about 100 mb the filingsList has about 8 million lines.</p> <pre><code>def getAllCIKS(filingList): cikDICT=defaultdict(int) for filing in filingList: if filing.startswith('.'): del(filing) continue cik=filing.split('^')[0].strip() cikDICT[cik]+=1 del(filing) ciklist=cikDICT.keys() ciklist.sort() return ciklist allCIKS=getAllCIKS(open(r'c:\filinglist.txt').readlines()) </code></pre> <p>If I run this instead I show an increase of almost 400 mb</p> <pre><code>cikDICT=defaultdict(int) for filing in open(r'c:\filinglist.txt').readlines(): if filing.startswith('.'): del(filing) continue cik=filing.split('^')[0].strip() cikDICT[cik]+=1 del(filing) ciklist=cikDICT.keys() ciklist.sort() del(cikDICT) </code></pre> <p>EDIT I have been playing around with this some more today. My observation and question should be refined a bit since my focus has been on the PF Usage. Unfortunately I can only poke at this between my other tasks. However I am starting to wonder about references versus copies. If I create a dictionary from a list does the dictionary container hold a copy of the values that came from the list or do they hold references to the values in the list? My bet is that the values are copied instead of referenced. </p> <p>Another thing I noticed is that items in the GC list were items from containers that were deleted. Does that make sense? Soo I have a list and suppose each of the items in the list was [(aTuple),anInteger,[another list]]. When I started learning about how to manipulate the gc objects and inspect them I found those objects in the gc even though the list had been forcefully deleted and even though I passed the 0,1 &amp; 2 value to the method that I don't remember to try to still delete them. </p> <p>I appreciate the insights people have been sharing. Unfortunately I am always interested in figuring out how things work under the hood. </p>
3
2009-05-28T03:52:02Z
948,246
<p>I asked another question about copying lists and the answers, particularly the answer directing me to look at deepcopy caused me to think about some dictionary behavior. The problem I was experiencing had to do with the fact that the original list is never garbage collected because the dictionary maintains references to the list. I need to use the information about weakref in the <a href="http://docs.python.org/library/weakref.html" rel="nofollow">Python Docs</a>.</p> <p>objects referenced by dictionaries seem to stay alive. I think (but am not sure) the process of pushing the dictionary out of the function forces the copy process and kills the object. This is not complete I need to do some more research.</p>
0
2009-06-04T01:55:24Z
[ "python", "memory-management", "function" ]
Problem in handle PNG by the PIL
919,104
<pre><code>from PIL import ImageFile as PILImageFile p = PILImageFile.Parser() #Parser the data for chunk in content.chunks(): p.feed(chunk) try: image = p.close() except IOError: return None #Here the model is RGBA if image.mode != "RGB": image = image.convert("RGB") </code></pre> <p>It always get stuck in here:</p> <pre><code>image = image.convert("RGB") File "C:\Python25\Lib\site-packages\PIL\Image.py" in convert 653. self.load() File "C:\Python25\Lib\site-packages\PIL\ImageFile.py" in load 189. s = read(self.decodermaxblock) File "C:\Python25\Lib\site-packages\PIL\PngImagePlugin.py" in load_read 365. return self.fp.read(bytes) File "C:\Python25\Lib\site-packages\PIL\ImageFile.py" in read 300. data = self.data[pos:pos+bytes] Exception Type: TypeError at Exception Value: 'NoneType' object is unsubscriptable </code></pre>
2
2009-05-28T03:52:35Z
18,046,944
<p>This results from an incorrect coding of close within PIL, its a bug.</p> <p><strong>Edit the File ( path may be different on your system ):</strong></p> <p><em>sudo vi /usr/lib64/python2.6/site-packages/PIL/ImageFile.py</em></p> <p><strong>Online 283 Modify:</strong></p> <pre><code>def close(self): self.data = self.offset = None </code></pre> <p><strong>Change it to:</strong></p> <pre><code>def close(self): #self.data = self.offset = None self.offset = None </code></pre> <p>Thats it, comment out the broken code, add the correct line, and save the file. All done, just run the program that was failing before and it will work now.</p>
0
2013-08-04T19:49:06Z
[ "python", "png", "python-imaging-library" ]
Scalable web application with lot of image servings
919,248
<p>I started working on a web application. This application needs lot of image handling. I started off with <a href="http://en.wikipedia.org/wiki/PHP" rel="nofollow">PHP</a> as it was the easiest and cheapest to host. I have used the .NET framework for some of my previous applications and I'm very comfortable with Python. </p> <p>But I'm not at all comfortable using PHP now, so I have decided to use something easier for me.</p> <p>Can anyone help me understand if the .NET framework or Python (currently web.py looks good to me) has some edge over others, considering a lot of image manipulation and let's say about 200 requests per second?</p> <p>Also I would appreciate if someone can suggest a proper host for either of them.</p> <p>EDIT:</p> <p>Sorry for the confusion. By image handling I mean the users of the application are allowed to upload pictures that would be stored in the flat file system while their entries are in the database.</p> <p>By image manipulation, I mean I would need to create thumbnails for these images too which would be used in the application.</p>
0
2009-05-28T05:02:08Z
919,339
<p>If you want performance when serving images, you have to take the FaceBook approach of 'never go to disk unless absolutely necessary' - meaning use as much caching as possible between your image servers and the end user. There are many products that can help you out both commercial and free, including just configuring your webservers correctly - google and see what works for your cost and platform.</p>
0
2009-05-28T05:39:47Z
[ ".net", "python", "scalability" ]
Scalable web application with lot of image servings
919,248
<p>I started working on a web application. This application needs lot of image handling. I started off with <a href="http://en.wikipedia.org/wiki/PHP" rel="nofollow">PHP</a> as it was the easiest and cheapest to host. I have used the .NET framework for some of my previous applications and I'm very comfortable with Python. </p> <p>But I'm not at all comfortable using PHP now, so I have decided to use something easier for me.</p> <p>Can anyone help me understand if the .NET framework or Python (currently web.py looks good to me) has some edge over others, considering a lot of image manipulation and let's say about 200 requests per second?</p> <p>Also I would appreciate if someone can suggest a proper host for either of them.</p> <p>EDIT:</p> <p>Sorry for the confusion. By image handling I mean the users of the application are allowed to upload pictures that would be stored in the flat file system while their entries are in the database.</p> <p>By image manipulation, I mean I would need to create thumbnails for these images too which would be used in the application.</p>
0
2009-05-28T05:02:08Z
919,469
<p>From what You have written, either .NET or Python would be a good choice for You. Personally, I would go for Python. Why?</p> <ul> <li>It is free.</li> <li>It is scalable.</li> <li>With Python Imaging Library You can do almost anything with images.</li> <li>Hey, it is python - less code, same result.</li> </ul> <p>To be honest Your choice is not important - just choose the one You feel comfortable with and stick with it.You mentioned web.py - this site is made with web.py: <a href="http://www.colr.org" rel="nofollow">colr.org</a> - and it is made with 1304 lines of code, not counting external libraries. </p>
0
2009-05-28T06:29:12Z
[ ".net", "python", "scalability" ]
Scalable web application with lot of image servings
919,248
<p>I started working on a web application. This application needs lot of image handling. I started off with <a href="http://en.wikipedia.org/wiki/PHP" rel="nofollow">PHP</a> as it was the easiest and cheapest to host. I have used the .NET framework for some of my previous applications and I'm very comfortable with Python. </p> <p>But I'm not at all comfortable using PHP now, so I have decided to use something easier for me.</p> <p>Can anyone help me understand if the .NET framework or Python (currently web.py looks good to me) has some edge over others, considering a lot of image manipulation and let's say about 200 requests per second?</p> <p>Also I would appreciate if someone can suggest a proper host for either of them.</p> <p>EDIT:</p> <p>Sorry for the confusion. By image handling I mean the users of the application are allowed to upload pictures that would be stored in the flat file system while their entries are in the database.</p> <p>By image manipulation, I mean I would need to create thumbnails for these images too which would be used in the application.</p>
0
2009-05-28T05:02:08Z
920,157
<p>Please buy Schlossnagle's book, <a href="http://rads.stackoverflow.com/amzn/click/067232699X" rel="nofollow">Scalable Internet Architectures</a>.</p> <p>You should not be serving the images from Python (or PHP or .Net) but from Apache and Squid. Same is true for Javascript and CSS files -- they're static media, and Python should never touch them. </p> <p>You should only be processing the HTML portion of the transaction.</p> <p>This, BTW, is the architecture you get with things like <a href="http://www.djangoproject.com" rel="nofollow">Django</a>. Static media is handled outside Python. Python handles validation and the HTML part of the processing.</p> <p>Turns out that you'll spend much of your time fussing around with Squid and Apache trying to get things to go quickly. Python (and the Django framework) are fast enough if you limit their responsibilities.</p>
1
2009-05-28T10:16:54Z
[ ".net", "python", "scalability" ]
Scalable web application with lot of image servings
919,248
<p>I started working on a web application. This application needs lot of image handling. I started off with <a href="http://en.wikipedia.org/wiki/PHP" rel="nofollow">PHP</a> as it was the easiest and cheapest to host. I have used the .NET framework for some of my previous applications and I'm very comfortable with Python. </p> <p>But I'm not at all comfortable using PHP now, so I have decided to use something easier for me.</p> <p>Can anyone help me understand if the .NET framework or Python (currently web.py looks good to me) has some edge over others, considering a lot of image manipulation and let's say about 200 requests per second?</p> <p>Also I would appreciate if someone can suggest a proper host for either of them.</p> <p>EDIT:</p> <p>Sorry for the confusion. By image handling I mean the users of the application are allowed to upload pictures that would be stored in the flat file system while their entries are in the database.</p> <p>By image manipulation, I mean I would need to create thumbnails for these images too which would be used in the application.</p>
0
2009-05-28T05:02:08Z
920,498
<p>I do not think switching languages will help much with your problem, It's just the architecture you chose initially only works for small amounts of data. I would recommend you to visit <a href="http://highscalability.com" rel="nofollow">http://highscalability.com</a> , It's time you started looking how the big guys scale their applications. </p>
0
2009-05-28T11:54:58Z
[ ".net", "python", "scalability" ]
Scalable web application with lot of image servings
919,248
<p>I started working on a web application. This application needs lot of image handling. I started off with <a href="http://en.wikipedia.org/wiki/PHP" rel="nofollow">PHP</a> as it was the easiest and cheapest to host. I have used the .NET framework for some of my previous applications and I'm very comfortable with Python. </p> <p>But I'm not at all comfortable using PHP now, so I have decided to use something easier for me.</p> <p>Can anyone help me understand if the .NET framework or Python (currently web.py looks good to me) has some edge over others, considering a lot of image manipulation and let's say about 200 requests per second?</p> <p>Also I would appreciate if someone can suggest a proper host for either of them.</p> <p>EDIT:</p> <p>Sorry for the confusion. By image handling I mean the users of the application are allowed to upload pictures that would be stored in the flat file system while their entries are in the database.</p> <p>By image manipulation, I mean I would need to create thumbnails for these images too which would be used in the application.</p>
0
2009-05-28T05:02:08Z
920,598
<p>As mentioned previously, any number of development platforms will work, it really depends on your approach to caching the content.</p> <p>If you are comfortable with Python I would recommend <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow">Django</a>. There is a large development community and a number of large applications and sites running on the framework.</p> <p>Django internally supports caching through use of <a href="http://en.wikipedia.org/wiki/Memcached" rel="nofollow">memcached</a>. You are able to customize quite greatly how and what you want to cache, while being able to keep many of the settings for the caching in your actual Django application (I find this nice when using third party hosting services where I do not have complete control of the system).</p> <p>Here are a few links that may help:</p> <ul> <li><a href="http://www.djangoproject.com" rel="nofollow">Django framework</a> - General information on the Django framework.</li> <li><a href="http://docs.djangoproject.com/en/dev/topics/cache/" rel="nofollow">Memcached with Django</a> - Covers how to configure caching specifically for a Django project.</li> <li><a href="http://danga.com/memcached/" rel="nofollow">Memcached website</a></li> <li><a href="http://www.djangobook.com/en/2.0/" rel="nofollow">The Django Book</a> - A free online book to learn Django (it also covers caching and scaling quetsions). <ul> <li><a href="http://www.djangobook.com/en/1.0/chapter20/" rel="nofollow">Scaling Chapter</a></li> <li><a href="http://www.djangobook.com/en/2.0/chapter15/" rel="nofollow">Caching Chapter</a></li> </ul></li> </ul> <p>There are a number of hosting companies that offer both shared and dedicated hosting plans. I would visit <a href="http://djangohosting.org/" rel="nofollow">http://djangohosting.org/</a> to determine which host may work best for your need. I have used <a href="http://www.webfaction.com" rel="nofollow">WebFaction</a> quite a bit and have been extremely pleased with their service.</p>
1
2009-05-28T12:31:02Z
[ ".net", "python", "scalability" ]
Scalable web application with lot of image servings
919,248
<p>I started working on a web application. This application needs lot of image handling. I started off with <a href="http://en.wikipedia.org/wiki/PHP" rel="nofollow">PHP</a> as it was the easiest and cheapest to host. I have used the .NET framework for some of my previous applications and I'm very comfortable with Python. </p> <p>But I'm not at all comfortable using PHP now, so I have decided to use something easier for me.</p> <p>Can anyone help me understand if the .NET framework or Python (currently web.py looks good to me) has some edge over others, considering a lot of image manipulation and let's say about 200 requests per second?</p> <p>Also I would appreciate if someone can suggest a proper host for either of them.</p> <p>EDIT:</p> <p>Sorry for the confusion. By image handling I mean the users of the application are allowed to upload pictures that would be stored in the flat file system while their entries are in the database.</p> <p>By image manipulation, I mean I would need to create thumbnails for these images too which would be used in the application.</p>
0
2009-05-28T05:02:08Z
931,199
<p>I would also recommend looking at <a href="http://www.danga.com/mogilefs/" rel="nofollow">MogileFS</a>. It is a distributed file system which runs on Unix based OS's. I know that digg use it to store their avatar images. </p> <p>It's from the same guys who created memcached and live journal.</p>
0
2009-05-31T03:36:19Z
[ ".net", "python", "scalability" ]
Resize ctypes array
919,369
<p>I'd like to resize a ctypes array. As you can see, ctypes.resize doesn't work like it could. I can write a function to resize an array, but I wanted to know some other solutions to this. Maybe I'm missing some ctypes trick or maybe I simply used resize wrong. The name c_long_Array_0 seems to tell me this may not work with resize.</p> <pre><code>&gt;&gt;&gt; from ctypes import * &gt;&gt;&gt; c_int * 0 &lt;class '__main__.c_long_Array_0'&gt; &gt;&gt;&gt; intType = c_int * 0 &gt;&gt;&gt; foo = intType() &gt;&gt;&gt; foo &lt;__main__.c_long_Array_0 object at 0xb7ed9e84&gt; &gt;&gt;&gt; foo[0] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IndexError: invalid index &gt;&gt;&gt; resize(foo, sizeof(c_int * 1)) &gt;&gt;&gt; foo[0] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IndexError: invalid index &gt;&gt;&gt; foo &lt;__main__.c_long_Array_0 object at 0xb7ed9e84&gt; &gt;&gt;&gt; sizeof(c_int * 0) 0 &gt;&gt;&gt; sizeof(c_int * 1) 4 </code></pre> <p>Edit: Maybe go with something like:</p> <pre><code>&gt;&gt;&gt; ctypes_resize = resize &gt;&gt;&gt; def resize(arr, type): ... tmp = type() ... for i in range(len(arr)): ... tmp[i] = arr[i] ... return tmp ... ... &gt;&gt;&gt; listType = c_int * 0 &gt;&gt;&gt; list = listType() &gt;&gt;&gt; list = resize(list, c_int * 1) &gt;&gt;&gt; list[0] 0 &gt;&gt;&gt; </code></pre> <p>But that's ugly passing the type instead of the size. It works for its purpose and that's it.</p>
3
2009-05-28T05:51:38Z
919,501
<pre><code>from ctypes import * list = (c_int*1)() def customresize(array, new_size): resize(array, sizeof(array._type_)*new_size) return (array._type_*new_size).from_address(addressof(array)) list[0] = 123 list = customresize(list, 5) &gt;&gt;&gt; list[0] 123 &gt;&gt;&gt; list[4] 0 </code></pre>
6
2009-05-28T06:47:36Z
[ "python", "ctypes" ]
How do we precompile base templates in Cheetah so that #include, #extends and #import works properly in Weby
919,539
<p>How do you serve <strong>Cheetah</strong> in <strong>production</strong>?</p> <p>Guys can you share the setup on how to precompile and serve cheetah in production</p> <p>Since we dont compile templates in webpy it is getting upstream time out errors. If you could share a good best practise it would help</p> <p>*</p> <blockquote> <p>Jeremy wrote: For a production site, I use Cheetah with pre-compiled templates - it's very fast (the templates import especially quickly when python compiled and optimised). A bit of magic with the imp module takes a template name and a base directory (configured in a site-specific config) and loads up that template, taking care of #extends and</p> <h1>import directives as appropriate. I don't use the built-in support for</h1> <p>Cheetah, however. The new template library is also only imported to display the debugerror page</p> </blockquote> <p>*</p>
2
2009-05-28T07:02:48Z
933,727
<p>Maybe compile automagically on as needed basis:</p> <pre><code>import sys import os from os import path import logging from Cheetah.Template import Template from Cheetah.Compiler import Compiler log = logging.getLogger(__name__) _import_save = __import__ def cheetah_import(name, *args, **kw): """Import function which search for Cheetah templates. When template ``*.tmpl`` is found in ``sys.path`` matching module name (and corresponding generated Python module is outdated or not existent) it will be compiled prior to actual import. """ name_parts = name.split('.') for p in sys.path: basename = path.join(p, *name_parts) tmpl_path = basename+'.tmpl' py_path = basename+'.py' if path.exists(tmpl_path): log.debug("%s found in %r", name, tmpl_path) if not path.exists(py_path) or newer(tmpl_path, py_path): log.info("cheetah compile %r -&gt; %r", tmpl_path, py_path) output = Compiler( file=tmpl_path, moduleName=name, mainClassName=name_parts[-1], ) open(py_path, 'wb').write(str(output)) break return _import_save(name, *args, **kw) def newer(new, old): """Whether file with path ``new`` is newer then at ``old``.""" return os.stat(new).st_mtime &gt; os.stat(old).st_mtime import __builtin__ __builtin__.__import__ = cheetah_import </code></pre>
1
2009-06-01T06:18:12Z
[ "python", "inheritance", "web.py" ]
How do we precompile base templates in Cheetah so that #include, #extends and #import works properly in Weby
919,539
<p>How do you serve <strong>Cheetah</strong> in <strong>production</strong>?</p> <p>Guys can you share the setup on how to precompile and serve cheetah in production</p> <p>Since we dont compile templates in webpy it is getting upstream time out errors. If you could share a good best practise it would help</p> <p>*</p> <blockquote> <p>Jeremy wrote: For a production site, I use Cheetah with pre-compiled templates - it's very fast (the templates import especially quickly when python compiled and optimised). A bit of magic with the imp module takes a template name and a base directory (configured in a site-specific config) and loads up that template, taking care of #extends and</p> <h1>import directives as appropriate. I don't use the built-in support for</h1> <p>Cheetah, however. The new template library is also only imported to display the debugerror page</p> </blockquote> <p>*</p>
2
2009-05-28T07:02:48Z
968,398
<p><strong>This works</strong></p> <pre><code>try:web.render('mafbase.tmpl', None, True, 'mafbase') except:pass </code></pre> <p><strong>This is what i did with you code</strong></p> <pre><code>from cheetahimport import * sys.path.append('./templates') cheetah_import('mafbase') </code></pre> <h1>includes dont work in the given method.</h1> <p><strong>This is the error i got</strong></p> <pre><code> localhost pop]$ vi code.py [mark@localhost pop]$ ./code.py 9911 http://0.0.0.0:9911/ Traceback (most recent call last): File "/home/mark/work/common/web/application.py", line 241, in process return self.handle() File "/home/mark/work/common/web/application.py", line 232, in handle return self._delegate(fn, self.fvars, args) File "/home/mark/work/common/web/application.py", line 411, in _delegate return handle_class(cls) File "/home/mark/work/common/web/application.py", line 386, in handle_class return tocall(*args) File "user.py", line 264, in proxyfunc return func(self, *args, **kw) File "/home/mark/work/pop/code.py", line 1801, in GET return web.render('subclass.html') File "/home/mark/work/common/web/cheetah.py", line 104, in render return str(compiled_tmpl) File "/usr/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux-i686.egg/Cheetah/Template.py", line 982, in __str__ def __str__(self): return getattr(self, mainMethName)() File "templates/mafbase.py", line 713, in respond self._handleCheetahInclude("widgetbox.html", trans=trans, includeFrom="file", raw=False) File "/usr/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux-i686.egg/Cheetah/Template.py", line 1512, in _handleCheetahInclude nestedTemplateClass = compiler.compile(source=source,file=file) File "/usr/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux-i686.egg/Cheetah/Template.py", line 693, in compile fileHash = str(hash(file))+str(os.path.getmtime(file)) File "/usr/lib/python2.5/posixpath.py", line 143, in getmtime return os.stat(filename).st_mtime OSError: [Errno 2] No such file or directory: '/home/mark/work/pop/widgetbox.html' </code></pre>
0
2009-06-09T06:00:17Z
[ "python", "inheritance", "web.py" ]
Can a variable number of arguments be passed to a function?
919,680
<p>In a similar way to using varargs in C or C++:</p> <pre><code>fn(a, b) fn(a, b, c, d, ...) </code></pre>
180
2009-05-28T07:50:10Z
919,684
<p>Yes.</p> <p>This is simple and works if you disregard keyword arguments:</p> <pre><code>def manyArgs(*arg): print "I was called with", len(arg), "arguments:", arg &gt;&gt;&gt; manyArgs(1) I was called with 1 arguments: (1,) &gt;&gt;&gt; manyArgs(1, 2,3) I was called with 3 arguments: (1, 2, 3) </code></pre> <p>As you can see, Python will give you a single tuple with all the arguments.</p> <p>For keyword arguments you need to accept those as a separate actual argument, as shown in <a href="http://stackoverflow.com/a/919720/28169">Skurmedel's answer</a>.</p>
229
2009-05-28T07:51:54Z
[ "python" ]
Can a variable number of arguments be passed to a function?
919,680
<p>In a similar way to using varargs in C or C++:</p> <pre><code>fn(a, b) fn(a, b, c, d, ...) </code></pre>
180
2009-05-28T07:50:10Z
919,720
<p>Adding to unwinds post:</p> <p>You can send multiple key-value args too.</p> <pre><code>def myfunc(**kwargs): # kwargs is a dictionary. for k,v in kwargs.iteritems(): print "%s = %s" % (k, v) myfunc(abc=123, efh=456) # abc = 123 # efh = 456 </code></pre> <p>And you can mix the two:</p> <pre><code>def myfunc2(*args, **kwargs): for a in args: print a for k,v in kwargs.iteritems(): print "%s = %s" % (k, v) myfunc2(1, 2, 3, banan=123) # 1 # 2 # 3 # banan = 123 </code></pre> <p>They must be both declared and called in that order, that is the function signature needs to be *args, **kwargs, and called in that order.</p>
146
2009-05-28T07:59:58Z
[ "python" ]
Can a variable number of arguments be passed to a function?
919,680
<p>In a similar way to using varargs in C or C++:</p> <pre><code>fn(a, b) fn(a, b, c, d, ...) </code></pre>
180
2009-05-28T07:50:10Z
9,449,581
<p>Adding to the other excellent posts.</p> <p>Sometimes you don't want to specify the number of arguments <strong>and</strong> want to use keys for them (the compiler will complain if one argument passed in a dictionary is not used in the method).</p> <pre><code>def manyArgs1(args): print args.a, args.b #note args.c is not used here def manyArgs2(args): print args.c #note args.b and .c are not used here class Args: pass args = Args() args.a = 1 args.b = 2 args.c = 3 manyArgs1(args) #outputs 1 2 manyArgs2(args) #outputs 3 </code></pre> <p>Then you can do things like</p> <pre><code>myfuns = [manyArgs1, manyArgs2] for fun in myfuns: fun(args) </code></pre>
9
2012-02-26T00:56:32Z
[ "python" ]
Can a variable number of arguments be passed to a function?
919,680
<p>In a similar way to using varargs in C or C++:</p> <pre><code>fn(a, b) fn(a, b, c, d, ...) </code></pre>
180
2009-05-28T07:50:10Z
16,785,702
<pre><code>def f(dic): if 'a' in dic: print dic['a'], pass else: print 'None', if 'b' in dic: print dic['b'], pass else: print 'None', if 'c' in dic: print dic['c'], pass else: print 'None', print pass f({}) f({'a':20, 'c':30}) f({'a':20, 'c':30, 'b':'red'}) ____________ </code></pre> <p>the above code will output</p> <pre><code>None None None 20 None 30 20 red 30 </code></pre> <p>This is as good as passing variable arguments by means of a dictionary</p>
2
2013-05-28T07:00:57Z
[ "python" ]
Progress bar with long web requests
919,816
<p>In a django application I am working on, I have just added the ability to archive a number of files (starting 50mb in total) to a zip file. Currently, i am doing it something like this:</p> <pre><code>get files to zip zip all files send HTML response </code></pre> <p>Obviously, this causes a big wait on line two where the files are being compressed. What can i do to make this processes a whole lot better for the user? Although having a progress bar would be the best, even if it just returned a static page saying 'please wait' or whatever.</p> <p>Any thoughts and ideas would be loved.</p>
2
2009-05-28T08:38:58Z
919,919
<p>Better than a static page, show a Javascript dialog (using Shadowbox, JQuery UI or some custom method) with a throbber ( you can get some at hxxp://www.ajaxload.info/ ). You can also show the throbber in your page, without dialogs. Most users only want to know their action is being handled, and can live without reliable progress information ("Please wait, this could take some time...")</p> <p>JQUery UI also has a progress bar API. You could make periodic AJAX queries to a didcated page on your website to get a progress report and change the progress bar accordingly. Depending on how often the archiving is ran, how many users can trigger it and how you authenticate your users, this could be quite hard.</p>
0
2009-05-28T09:10:37Z
[ "python", "django" ]
Progress bar with long web requests
919,816
<p>In a django application I am working on, I have just added the ability to archive a number of files (starting 50mb in total) to a zip file. Currently, i am doing it something like this:</p> <pre><code>get files to zip zip all files send HTML response </code></pre> <p>Obviously, this causes a big wait on line two where the files are being compressed. What can i do to make this processes a whole lot better for the user? Although having a progress bar would be the best, even if it just returned a static page saying 'please wait' or whatever.</p> <p>Any thoughts and ideas would be loved.</p>
2
2009-05-28T08:38:58Z
919,935
<p>You should keep in mind showing the progress bar may not be a good idea, since you can get timeouts or get your server suffer from submitting lot of simultaneous requests.</p> <p>Put the zipping task in the queue and have it callback to notify the user somehow - by e-mail for instance - that the process has finished.</p> <p>Take a look at <a href="http://code.google.com/p/django-lineup/" rel="nofollow">django-lineup</a></p> <p>Your code will look pretty much like:</p> <pre><code>from lineup import registry from lineup import _debug def create_archive(queue_id, queue): queue.set_param("zip_link", _create_archive(resource = queue.context_object, user = queue.user)) return queue def create_archive_callback(queue_id, queue): _send_email_notification(subject = queue.get_param("zip_link"), user = queue.user) return queue registry.register_job('create_archive', create_archive, callback = create_archive_callback) </code></pre> <p>In your views, create queued tasks by:</p> <pre><code> from lineup.factory import JobFactory j = JobFactory() j.create_job(self, 'create_archive', request.user, your_resource_object_containing_files_to_zip, { 'extra_param': 'value' }) </code></pre> <p>Then run your queue processor (probably inside of a screen session):</p> <pre><code>./manage.py run_queue </code></pre> <p>Oh, and on the subject you might be also interested in <a href="http://stackoverflow.com/questions/767684/estimating-zip-size-creation-time">estimating zip file creation time</a>. I got pretty slick answers there.</p>
3
2009-05-28T09:15:37Z
[ "python", "django" ]
Progress bar with long web requests
919,816
<p>In a django application I am working on, I have just added the ability to archive a number of files (starting 50mb in total) to a zip file. Currently, i am doing it something like this:</p> <pre><code>get files to zip zip all files send HTML response </code></pre> <p>Obviously, this causes a big wait on line two where the files are being compressed. What can i do to make this processes a whole lot better for the user? Although having a progress bar would be the best, even if it just returned a static page saying 'please wait' or whatever.</p> <p>Any thoughts and ideas would be loved.</p>
2
2009-05-28T08:38:58Z
919,955
<p>You could use a 'log-file' to keep track of the zipped files, and of how many files still remain.</p> <p>The procedural way should be like this:</p> <ol> <li>Count the numbers of file, write it in a text file, in a format like totalfiles.filespreocessed</li> <li>Every file you zip, simply update the file</li> </ol> <p>So, if you have to zip 3 files, the log file will grown as:</p> <pre><code>3.0 -&gt; begin, no file still processed 3.1 -&gt; 1 file on 3 processed, 33% task complete 3.2 -&gt; 2 file on 3 processed, 66% task complete 3.3 -&gt; 3 file on 3 processed, 100% task complete </code></pre> <p>And then with a simple ajax function (an interval) check the log-file every second.</p> <p>In python, open, read and rite a file such small should be very quick, but maybe can cause some requests trouble if you'll have many users doing that in the same time, but obviously you'll need to create a log file for each request, maybe with rand name, and delete it after the task is completed.</p> <p>A problem could be that, for let the ajax read the log-file, you'll need to open and close the file handler in python every time you update it.</p> <p>Eventually, for a more accurate progress meter, you culd even use the file size instead of the number of file as parameter.</p>
0
2009-05-28T09:21:27Z
[ "python", "django" ]
Progress bar with long web requests
919,816
<p>In a django application I am working on, I have just added the ability to archive a number of files (starting 50mb in total) to a zip file. Currently, i am doing it something like this:</p> <pre><code>get files to zip zip all files send HTML response </code></pre> <p>Obviously, this causes a big wait on line two where the files are being compressed. What can i do to make this processes a whole lot better for the user? Although having a progress bar would be the best, even if it just returned a static page saying 'please wait' or whatever.</p> <p>Any thoughts and ideas would be loved.</p>
2
2009-05-28T08:38:58Z
921,447
<p>Fun fact: You might be able to use a progress bar to trick users into thinking that things are going faster than they really are.</p> <p><a href="http://www.chrisharrison.net/projects/progressbars/index.html" rel="nofollow">http://www.chrisharrison.net/projects/progressbars/index.html</a></p>
0
2009-05-28T15:21:38Z
[ "python", "django" ]
How to find a thread id in Python
919,897
<p>I have a multi-threading Python program, and a utility function, writeLog(message), that writes out a timestamp followed by the message. Unfortunately, the resultant log file gives no indication of which thread is generating which message. </p> <p>I would like writeLog() to be able to add something to the message to identify which thread is calling it. Obviously I could just make the threads pass this information in, but that would be a lot more work. Is there some thread equivalent of os.getpid() that I could use?</p>
68
2009-05-28T09:04:24Z
919,920
<p>I saw examples of thread IDs like this:</p> <pre><code>class myThread(threading.Thread): def __init__(self, threadID, name, counter): self.threadID = threadID ... </code></pre> <p>The <a href="http://docs.python.org/library/threading.html#threading.Thread.name">threading module docs</a> lists <code>name</code> attribute as well:</p> <pre><code>... A thread has a name. The name can be passed to the constructor, and read or changed through the name attribute. ... Thread.name A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. </code></pre>
5
2009-05-28T09:11:13Z
[ "python", "multithreading" ]
How to find a thread id in Python
919,897
<p>I have a multi-threading Python program, and a utility function, writeLog(message), that writes out a timestamp followed by the message. Unfortunately, the resultant log file gives no indication of which thread is generating which message. </p> <p>I would like writeLog() to be able to add something to the message to identify which thread is calling it. Obviously I could just make the threads pass this information in, but that would be a lot more work. Is there some thread equivalent of os.getpid() that I could use?</p>
68
2009-05-28T09:04:24Z
919,928
<p><a href="http://docs.python.org/library/threading.html#threading.Thread.ident"><code>thread.get_ident()</code></a> works, though <code>thread</code> is deprecated, or <a href="http://docs.python.org/library/threading.html#threading.current_thread"><code>threading.current_thread()</code></a> (or <code>threading.currentThread()</code> for Python &lt; 2.6).</p>
85
2009-05-28T09:13:40Z
[ "python", "multithreading" ]
How to find a thread id in Python
919,897
<p>I have a multi-threading Python program, and a utility function, writeLog(message), that writes out a timestamp followed by the message. Unfortunately, the resultant log file gives no indication of which thread is generating which message. </p> <p>I would like writeLog() to be able to add something to the message to identify which thread is calling it. Obviously I could just make the threads pass this information in, but that would be a lot more work. Is there some thread equivalent of os.getpid() that I could use?</p>
68
2009-05-28T09:04:24Z
2,357,652
<p>Using the <a href="http://docs.python.org/library/logging.html">logging</a> module you can automatically add the current thread identifier in each log entry. Just use one of these <a href="http://docs.python.org/library/logging.html#logging.LogRecord">LogRecord</a> mapping keys in your logger format string:</p> <blockquote> <p><em>%(thread)d :</em> Thread ID (if available).</p> <p><em>%(threadName)s :</em> Thread name (if available).</p> </blockquote> <p>and set up your default handler with it:</p> <pre><code>logging.basicConfig(format="%(threadName)s:%(message)s") </code></pre>
37
2010-03-01T17:19:18Z
[ "python", "multithreading" ]
How to find a thread id in Python
919,897
<p>I have a multi-threading Python program, and a utility function, writeLog(message), that writes out a timestamp followed by the message. Unfortunately, the resultant log file gives no indication of which thread is generating which message. </p> <p>I would like writeLog() to be able to add something to the message to identify which thread is calling it. Obviously I could just make the threads pass this information in, but that would be a lot more work. Is there some thread equivalent of os.getpid() that I could use?</p>
68
2009-05-28T09:04:24Z
9,410,056
<p>The <code>thread.get_ident()</code> return long integer on linux, it's not really thread id. I use <a href="http://blog.devork.be/2010/09/finding-linux-thread-id-from-within.html" rel="nofollow">this method</a> get really thread id on linux.</p> <pre><code>import ctypes libc = ctypes.cdll.LoadLibrary('libc.so.6') def getThreadId(): """Returns OS thread id - Specific to Linux""" return libc.syscall(186) # SYS_gettid value - System dependent </code></pre>
4
2012-02-23T09:17:44Z
[ "python", "multithreading" ]