Unexpected timing results with file I/O
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Mon Feb 4 13:04:49 EST 2008
En Mon, 04 Feb 2008 15:53:11 -0200, rdahlstrom <roger.dahlstrom at gmail.com>
escribi�:
> On Feb 4, 10:17 am, Steven D'Aprano <st... at REMOVE-THIS-
> cybersource.com.au> wrote:
>>
>> Suppose you have a whole lot of files, and you need to open each one,
>> append a string, then close them. There's two obvious ways to do it:
>> group your code by file, or group your code by procedure.
>>
>> # Method one: grouped by file.
>> for each file:
>> open the file, append the string, then close it
>>
>> # Method two: grouped by procedure.
>> for each file:
>> open the file
>> for each open file:
>> append the string
>> for each open file:
>> close the file
>>
>> If you have N files, both methods make the same number of I/O calls: N
>> opens, N writes, N closes. Which is faster?
> The code that does more work takes more time. The second one does
> quite a bit less work. Think of it like this:
>
> You have 500,000 people to fit through a door. Here are your options:
>
> 1. For each person, open the door, walk through the door, then close
> the door.
> 2. Open the door, allow everyone to walk through, then close the
> door.
>
> Which one would you say would be a more efficient way to fit 500,000
> people through the door?
Mmmm, no, the second one should be:
2. Create 500,000 doors and open them.
Make each person enter the room -one at a time- using its own door.
Close each of the 500,000 doors.
--
Gabriel Genellina
More information about the Python-list
mailing list