Python / C: small runtime difference?

Tim Hochberg tim.hochberg at ieee.org
Fri Sep 12 13:56:57 EDT 2003


Alan Gauld wrote:
> On Tue, 9 Sep 2003 15:54:41 +0200, "Martin Schneider"
> <martin.schneider at illusion-factory.de> wrote:
> 
> 
>>for i in range(len(fileList)-1):
>> for j in range(len(fileList)-i-1):
>>  if fileList[j+1] < fileList[j]:
>>   tmp = fileList[j]
>>   fileList[j] = fileList[j+1]
>>   fileList[j+1] = tmp
> 
> 
> I think you might tweak that by doing:
> 
> fileList[j],fileList[j+1] = fileList[j+1],fileList[j]
> 
> which misses out the intermediate tmp assignment.

Careful here. You'd have to time it to be sure, but the above is 
probably slower than what you're replacing.  The reason is that the
above creates an anonymous tuple then unpacks it. More or less 
equivalent to:

tmp = (fileList[j+1], fileList[j])
fileList[j], fileList[j+1] = tmp

I'd be tempted to do it anyway in all but the tightest loops as I think 
it's clearer.

-tim

> If you are gonna tweak the C you might as well tweak the 
> Python too! (But not with a real python, they tweak back 
> hard! :-)
> 
> Alan G.
> Author of the Learn to Program website
> http://www.freenetpages.co.uk/hp/alan.gauld





More information about the Python-list mailing list