473,889 Members | 1,716 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

puts() vs printf()

I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:

puts("Some random text");

vs.

printf("Some random text\n");

[Read: no formatting.]
Would anyone please confirm or deny this? It makes sense since
printf() uses vargs, but I'd like some confirmation. The author uses
void main() so I'm not sure what to think. Given today's hardware and
compiler optimizations I have no idea if it even matters. I'm not very
good at modern-day assembly, so I can't compare it that way.
I've generally steered away from the puts-gets I/O functions in the
past. I don't know why this is the case...maybe it has to do with
consistency as I don't always want the newline automatically output.

What's the word?

Thanks.

p.s. The book is by Herb Schlidt (or something similar) if that's any
indication.
Aug 24 '06
36 35603
Eric Sosman wrote:
>
.... snip ...
>
A former colleague who had labored as a compiler writer
for a large computer company (now defunct) told me he *did*
put this transformation into their compiler. Why? Because
parts of the SPEC benchmark suite used many "non-converting"
printf() calls, and by switching to puts() they raised their
SPEC scores without the silly bother of needing to make the
machine any faster. The improvement was only a milliwhisker
or two, but a computer maker will jump through a lot of hoops
for the appearance of greater speed ("As measured on industry-
standard benchmarks!").
Yet it did make that system faster in general. It also probably
reduced the object size of some fraction of programs. The fact
that its effects were exagerrated by the benchmark is just a bonus
:-)

--
Chuck F (cb********@yah oo.com) (cb********@mai neline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.netUSE maineline address!
Aug 24 '06 #11
"Debaser" <x@x.comwrote in message
news:hk******** *************** *********@4ax.c om...
I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:

puts("Some random text");

vs.

printf("Some random text\n");

[Read: no formatting.]
Would anyone please confirm or deny this? It makes sense since
printf() uses vargs, but I'd like some confirmation. The author uses
void main() so I'm not sure what to think. Given today's hardware and
compiler optimizations I have no idea if it even matters.
A modern compiler will notice when a single argument to printf()
contains no format specifiers and replace the call with puts() --
assuming it can strip the final '\n' at compile time.

I personally prefer using printf() for all output because then I don't
have to deal with forgetting the implicit '\n' that puts() adds.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Aug 24 '06 #12
Eric Sosman wrote:
jaapsch wrote:
>>
I would have thought that in this case (where the string to be printed
is a supplied literal string), the compiler would be able to optimise
it into a puts() call. I suppose it would first have to replace any
"%%" with "%" and so on.
As you said, it is likely a micro-optimisation that is probably not
worth the effort for compiler writers.

Compiler writers obey strange masters.
<snip optimising printf to puts>
Standardized benchmarks can be helpful measurement tools,
but they're rotten policy drivers.
In my opinion it is not a completely silly optimisation to do, it is
just one more example of strength reduction, although not necessarily
one that is high priority to implement. However, if it has a noticeable
effect on benchmark results then the benchmark is possibly not as good
as it should be.
--
Flash Gordon
Aug 24 '06 #13
Debaser wrote:
I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:

puts("Some random text");

vs.

printf("Some random text\n");

I would use puts() in this case, just because it's the routine made for
that operation. Less typing too. With no conversions to perform, I'd
only use printf() if I didn't want an automatic newline.


Brian (clarity not speed is the determing factor)
Aug 24 '06 #14
Stephen Sprunk wrote:
"Debaser" <x@x.comwrote in message
news:hk******** *************** *********@4ax.c om...
>I've recently read in one of my old C books that puts() is a better
function call with regard to performance than printf() in the
following situation:

puts("Some random text");

vs.

printf("Some random text\n");

[Read: no formatting.]
Would anyone please confirm or deny this? It makes sense since
printf() uses vargs, but I'd like some confirmation. The author uses
void main() so I'm not sure what to think. Given today's hardware and
compiler optimizations I have no idea if it even matters.

A modern compiler will notice when a single argument to printf()
contains no format specifiers and replace the call with puts() --
assuming it can strip the final '\n' at compile time.

I personally prefer using printf() for all output because then I don't
have to deal with forgetting the implicit '\n' that puts() adds.

S
Slightly wandering OT: Tried my example (see my other response in this
thread) with gcc optimization enabled and ONLY when the string is a
literal or a #defined constant it looks as if execution times are
identical, which may be (and probably is) indicative of printf() being
replaced by the faster puts(). Declaring the string (even as const)
*char does not convince gcc to use puts() in stead of printf(), at least
not here.

Would you say that gcc is a modern or old compiler based on this?
Sh.
Aug 24 '06 #15
Robert Gamble wrote:
I would have thought that in this case (where the string to be printed
is a supplied literal string), the compiler would be able to optimise
it into a puts() call. I suppose it would first have to replace any
"%%" with "%" and so on.
As you said, it is likely a micro-optimisation that is probably not
worth the effort for compiler writers.

Actually, gcc does do just that for string literals that end with a
newline and don't contain %.
gcc also changes 'printf("%s\n", str)' into 'puts(str)'.

$ gcc -S -O2 -x c - -o -
#include <stdio.h>
extern char *p;
int main(void) { printf("%s\n", p); return 0; }
^D .file ""
.text
.p2align 2,,3
..globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
andl $-16, %esp
subl $28, %esp
pushl p
call puts
xorl %eax, %eax
leave
ret
.size main, .-main
.ident "GCC: (GNU) 3.4.4 [FreeBSD] 20050518"

Aug 24 '06 #16
"Schraalhan s Keukenmeester" <fi************ ********@xsfour all.ennel>
wrote in message news:44******** **************@ news.xs4all.nl. ..
Stephen Sprunk wrote:
>A modern compiler will notice when a single argument to printf()
contains no format specifiers and replace the call with puts() --
assuming it can strip the final '\n' at compile time.

I personally prefer using printf() for all output because then I
don't
have to deal with forgetting the implicit '\n' that puts() adds.

Slightly wandering OT: Tried my example (see my other response in this
thread) with gcc optimization enabled and ONLY when the string is a
literal or a #defined constant it looks as if execution times are
identical, which may be (and probably is) indicative of printf() being
replaced by the faster puts(). Declaring the string (even as const)
*char does not convince gcc to use puts() in stead of printf(), at
least
not here.

Would you say that gcc is a modern or old compiler based on this?
Sh.
My experience plus Racaille's report in another post lead me to say it's
modern, i.e. doing something reasonably clever as I described. It's
curious that it doesn't convert a printf(char*) to puts(char*) but does
with literals, but there may be some reason for that or it might be a
bug (at least in your version).

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Aug 24 '06 #17
Flash Gordon wrote:
>
.... snip ...
>
<snip optimising printf to puts>
Standardized benchmarks can be helpful measurement tools,
but they're rotten policy drivers.

In my opinion it is not a completely silly optimisation to do, it
is just one more example of strength reduction, although not
necessarily one that is high priority to implement. However, if
it has a noticeable effect on benchmark results then the
benchmark is possibly not as good as it should be.
If that optimization manages to remove ALL references to printf,
then there is no need to load all that monstrous output
interpreter, and there can be significant reduction in the size of
the output code.

Fighting bloat at every turn :-)

--
Chuck F (cb********@yah oo.com) (cb********@mai neline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.netUSE maineline address!
Aug 24 '06 #18
Stephen Sprunk wrote:
>
.... snip ...
>
My experience plus Racaille's report in another post lead me to
say it's modern, i.e. doing something reasonably clever as I
described. It's curious that it doesn't convert a printf(char*)
to puts(char*) but does with literals, but there may be some
reason for that or it might be a bug (at least in your version).
It can't. The output of the two statements is different.

--
Chuck F (cb********@yah oo.com) (cb********@mai neline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.netUSE maineline address!
Aug 25 '06 #19

jaysome wrote:
On Wed, 23 Aug 2006 21:33:08 -0400, Eric Sosman
<es*****@acm-dot-org.invalidwrot e:
[snip]
It has been observed that Schildt's "The Annotated C Standard"
costs less than the Standard itself, and it has been opined that
the difference in price reflects the value of the annotations.

That and the fact that the middle of 7.6.9.1 is omitted because the
preceding page is duplicated.

Aug 25 '06 #20

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

Similar topics

24
5893
by: Charles Ulrich | last post by:
Greetings, I hope my greenness isn't showing too bad by asking this, but I ran across this trivial program today that left me flabbergasted: #define MESSAGE "This account is currently not available.\n" int main(int argc, char *argv) {
188
17522
by: infobahn | last post by:
printf("%p\n", (void *)0); /* UB, or not? Please explain your answer. */
4
1852
by: I_have_nothing | last post by:
Hi! Is there any easy way to printf an integer in a way like 1,234,567? I know "%d" can be usd to print it as 1234567. Any type field in format specification can do that? Or any easy way to do that? How about to do that same thing in float type? such as make 987564321.85 into 987,564,321.85 ?
8
15505
by: jchludzinski | last post by:
Is there a format specification for printf that will result in: 1000000 being printed as 1,000,000? Or 1000000.0 as 1,000,000.0? ---John
69
5629
by: fieldfallow | last post by:
Hello all, Before stating my question, I should mention that I'm fairly new to C. Now, I attempted a small demo that prints out the values of C's numeric types, both uninitialised and after assigning them their maximum defined values. However, the output of printf() for the long double 'ld' and the pointer of type void 'v_p', after initialisation don't seem to be right. The compiler used was gcc (mingw) with '-Wall', '-std=c99' and
18
2871
by: sam_cit | last post by:
Hi Everyone, int main() { printf("not included stdio.h"); } Yes, i haven't included stdio.h and my compiler would generate a warning and would assume that it would return a int, my question is how does the linker manage to link the function invocation to the proper
11
2688
by: vectorizor | last post by:
Hi guys, My program deals with with lots of large matrices. To easily debug it, I would like to be able to dump them in files, so that I can easily import then in other software (think matlab, excel) so I can analyse the intermediate results. To make sure the data can be understood by other programs, a space need to be included between each cell, and a return at the end of each row (row-major order). Hence at the moment, the dump code...
6
18068
by: MikeC | last post by:
Folks, Can the width specifier be used in a printf() text string? If I execute... printf("%4s", ".........."); it prints ten dots. If I execute
20
6870
by: Sanchit | last post by:
I want to know how does printf (stdio library function) works? Does this depand on complier (I am using gcc on Linix) Does it uses some buffer in which it stores all what needed to be printed and in end of program it prints that or something else.
0
9967
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11202
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
10792
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...
0
9611
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
7998
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
5830
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...
1
4650
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4251
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3256
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.