473,804 Members | 2,983 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why is "for line in f" faster than readline()

Hi,

In a recent thread I discovered why the "for line in f" idiom was not
suitable for live sources (pipes, sockets, tty).
The reason is that it uses buffering on input, blocking on a full
buffer read before anything.
When I asked why it did it this way, the answer came up that it made
it faster.

Now, *why* is such buffering gaining speed over stdio's fgets(), which
already does input buffering (though in a more subtle way, which makes
it still usable with pipes etc.) ?

-Alex

Jul 26 '07 #1
2 2987
Alexandre Ferrieux <al************ ****@gmail.comw rote:
Now, *why* is such buffering gaining speed over stdio's fgets(), which
already does input buffering (though in a more subtle way, which makes
it still usable with pipes etc.) ?
Because the C runtime library has different constraints than Python's file
iterator.

In particular the stdio fgets() must not read ahead (because the stream
might not be seekable), so it is usually just implemented as a series of
calls to read one character at a time until it has sufficient characters.
That inevitably has a lot more overhead than reading one 8k buffer and
subsequently splitting it up into lines.

It would probably be possible to do an implementation of fgets which looked
at the underlying stream and used buffering and seeking when the stream was
seekable and the cautious approach otherwise, but that isn't what is
usually done, and the incentive to do it isn't there: fgets() exists and
works as advertised even if it isn't very efficient. Anyone worried about
speed won't use it anyway, so improving it on specific platforms wouldn't
really help.

A lot of the C runtime is like that: it needs to be robust in a very
general purpose environment, but it doesn't need to be efficient. If you
are worried about efficiency then you should look elsewhere.
Jul 27 '07 #2
On Jul 27, 2:16 pm, Duncan Booth <duncan.bo...@i nvalid.invalidw rote:
Alexandre Ferrieux <alexandre.ferr i...@gmail.comw rote:
Now, *why* is such buffering gaining speed over stdio's fgets(), which
already does input buffering (though in a more subtle way, which makes
it still usable with pipes etc.) ?

Because the C runtime library has different constraints than Python's file
iterator.

In particular the stdio fgets() must not read ahead (because the stream
might not be seekable), so it is usually just implemented as a series of
calls to read one character at a time until it has sufficient characters.
Sorry, but this is simply wrong. Try an strace on a process doing
fgets(), and you'll see that it does
large read()s. Moreover, the semantics of a blocking read on those
live sources is to block while there are no more data, but to return
whatever's available (possibly fewer bytes than asked) as soon as new
data arrive.

This is the key to libc's performance in both line-by-line or bulk
transfers.

In fact, the Python file iterator is not faster than fgets() by the
way. It's just faster than the Python-wrapped version of it, readline,
which you said is just a thin layer above fgets(). So instead of
dismissing too quickly ol'good libc, maybe the investigation could
uncover a slight suboptimality in readline...
Anyone worried about
speed won't use it anyway, so improving it on specific platforms wouldn't
really help.
Oh really ? grep, sed, awk, all these stdio-based tools, are pathetic
snails compared to the Python file iterator, of course. But then, why
didn't anyone feel the urge to use this very same trick in C and
provide an "fgets2()", working only on seekable devices, but so much
faster ?

-Alex
Jul 27 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4969
by: leroybt.rm | last post by:
I don't understand why this does not work: <FILE1> test1.py #Import Packages import string # data=0 data=data+1
11
2175
by: David Morgenthaler | last post by:
How does one overide the iterator implied by the construct "for line in file:"? For example, suppose I have a file containing row,col pairs on each line, and I wish to write a subclass of file that will transform these to x,y coordinates using an affine transform. I'd like it to look something like this (but this clearly doesn't work): class myFile(file): def __init__(self,name,affine):
9
5813
by: Peter Hansen | last post by:
The term "mock filesystem" refers to code allowing unit or acceptance tests to create, read and write, and manipulate in other ways "virtual" files, without any actual disk access. Everything is held in memory and therefore fast, without risk of damaging real files, and with none of the messiness of leftover files after testing. Googling the archives and the web suggests that only I and Remy Blank have done much along these lines. I...
17
4726
by: John Grandy | last post by:
What is the C# equivalent to the VB.Net looping structure: Protected rbl As RadioButtonList Dim li As ListItem For Each li In rbl.Items Next li
5
4977
by: TJS | last post by:
trying to display pdf file in browser fails on this line: Response.ContentType = "application/pdf" getting an error about no declaration found for "response" what declaration is needed ???
12
13924
by: Emi Lu | last post by:
Hello all, I have a question about "date" & "timestamp" types in PostgreSQL. I want to setup the default value '0000-00-00' and "0000-00-00 00:00:00" for them. However, it seems that PostgreSQL does not support it. Could someone helps me please? The example table: T1 (col1 varchar(7) not null,
10
1764
by: Rafi B. | last post by:
I'm running this on a Linux/CentOs/cPanel server, trying to add caching to my PHP5 code, using ADOdb. I have two Linux servers, one of them is running perfect, the second one, just crashes without any error, and just gives a blank screen. I narrowed down the problem to: $line.serialize($rs2) Am I missing something maybe in the PHP5 configuration?
4
4725
by: Jacob Rael | last post by:
I am new to python and I love it. I am hacking a file. I want to not print a line if it contains the word 'pmos4_highv'. I also don't want to print the next line. The following code works but it "smells bad" and just doesn't look right. I was reading about generators. If I was using one, I could do a .next() after the match and get rid of the flags. Any suggestions how I can improve this? inPmos = False
2
2035
by: -Lost | last post by:
I have been watching code execution in various situations and I have noticed something. On the first test my example gave me obvious results. One method was far faster than the other. However, upon executing the code again (without refreshing the browser) the two tests were almost identical in speed. I am not sure if this has something to do specifically with JavaScript (and/or its engine) or if this is just something browsers try...
0
10568
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10323
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10311
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10074
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9138
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7613
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5516
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2988
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.