473,801 Members | 2,304 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 #1
36 35560
In article <hk************ *************** *****@4ax.com>,
Debaser <x@x.comwrote :
>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.
printf() -likely- calls va_init() unconditionally , but after that
there would be no arguments to process as there are no format
elements. Calling or not calling va_init() would be a constant time
factor, probably nearly undetectable.

printf() must examine each character at least once in order to
figure out that it is -not- a format character. If it is using
putc() to output characters, then in theory it could just output
each character immediately. It needs to test each character to
see if it is \0 anyhow, but two comparisons per character
instead of one might detectable on long enough strings.

If printf() is implimented by printing the entire string into a buffer
first, such as by calling sprintf() and then outputing the resulting
string, then the overhead of doing that would likely be detectable.

If you think about it, you will see that there is effectively
no way for printf() to do -less- work than puts() does: if there
were then puts() would use that method instead. The questions then
becomes one of QOI (Quality of Implementation) , together with
a question about instruction set architecture. In theory, two
tests per loop is not *necessarily* any slower than one, as there
could be an instruction that was effectively "move string until
delimeter", or the two tests might be overlapped, or the tight
loop could be micro-optimized. (The instruction set visible to
the programming level is often not the instruction set used
internally: microcoding is quite common.)
--
If you lie to the compiler, it will get its revenge. -- Henry Spencer
Aug 24 '06 #2
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");

[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.
puts(str) is usually faster than printf(str) because it
doesn't need to search through `str' for conversion specifications
like "%d". (Note that if `str' contains anything that looks
even vaguely like a conversion specification, printf(str) will
be in deep trouble -- printf("categor y\tcount\t%freq uency\n")
is most definitely a no-no.)

That said, the difference is likely to be so small that it's
unnoticeable, probably even so small that it will be difficult
to measure. Consider: You've got actual data output operations
going on, in order to deliver the printf()/puts() characters to
their destination -- disk file, pipe, cable modem with WhizFiber,
or whatever. All of these channels are VASTLY slower than the
CPU that executes the function call; by switching to the "more
efficient" variety you may be doing nothing more than increasing
the iteration count of the idle loop.

A friend of mine once described this sort of optimization as
"Cleaning the bottle tops off the beach so the sand will be nice
and clean around the beached whale carcases." Ponder that.
p.s. The book is by Herb Schlidt (or something similar) if that's any
indication.
I, personally, have never read any of Herr Schildt's works.
Others have, and have commented on them more perspicaciously than
I could; see, for example,

http://www.lysator.liu.se/c/schildt.html

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.

--
Eric Sosman
es*****@acm-dot-org.invalid
Aug 24 '06 #3
On Wed, 23 Aug 2006 20:23:20 -0400, Debaser <x@x.comwrote :
>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
It is strictly a quality of implementation issue. I personally
believe the assertion is generally true but that and a quarter still
won't buy you a cup of coffee.
>printf() uses vargs, but I'd like some confirmation. The author uses
Not because of variable arguments but because puts is a single minded
function (send an already formatted string to stdout) while printf has
so many bells and whistles that it "should" take more time to figure
out what it is you really want to do is the same.

It is also possible that some clever library writer decided this
degenerative use of printf is so common that a special check is made
early in the code and therefore the difference is immeasurably small.
>void main() so I'm not sure what to think. Given today's hardware and
A lot of books do unfortunately but it still serves as a reminder that
the author is prone to carelessness.
>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.
Be afraid, be very afraid!
Remove del for email
Aug 24 '06 #4
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");
.... snip ...
>
p.s. The book is by Herb Schlidt (or something similar) if
that's any indication.
It is. BullSchildt is normally error infested. In this particular
case he is right. This is analagous to undefined behaviour -
sometimes you get the expected result.

--
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 #5
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.
It's actually "The Annotated ANSI C Standard", ISBN 0-07-881952-0.

It has the text of the ANSI/ISO 9899-1990 standard on the left-hand
pages and Herbert's comments on the right-hand pages.

Unless I'm in need of a good laugh, I close my right eye when reading
this book. Both eyes open or not, it makes for real good reading--well
worth the price--providing you can find it.

It's unfortunate that someone like Steve Summit didn't write this
book.

Regards
--
jay
Aug 24 '06 #6
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");

[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.
When in doubt of relative speed of alternatives, you could put both
solutions to the test. A longer test run probably is more accurate than
a single loop.

#define RUNS 1000000UL
int main (void)
{
unsigned long i;
for (i=0;i<RUNS;i++ ) {
printf("stuff\n ");
// puts("stuff"); alternate with printf.
}
return 0;
}

Then compile and run the program. If your OS has no standard timer you
could use a built-in timer in the program, or time manually (but then
you really want long runs for reliability/accuracy). *nix offers you the
command time which shows you user, system and real time used by the
program. Simply recompile with the different options enabled and go.
>$ time ./a.out
should do the trick, where a.out is the default binary file name created
by gcc. Output-related measurements are more accurate/reliable when the
output is redirected to the bitbucket.

I just ran this example on my own system:

1 mln runs with printf() // 8 char string (or 9, including \n)
time ( ./a.out &/dev/null )
real 0m1.214s
user 0m1.207s
sys 0m0.006s

1 mln runs with puts() // 8 char string
time ( ./a.out &/dev/null )
real 0m0.552s
user 0m0.546s
sys 0m0.004s

So puts() is substantially faster in this case. With longer strings the
relative difference increases.

time ( ./a.out &/dev/null ) // printf(), 100 char string
real 0m4.174s
user 0m4.128s
sys 0m0.042s

time ( ./a.out &/dev/null ) // puts(), 100 char string
real 0m1.484s
user 0m1.443s
sys 0m0.036s

I wonder how often one has to output a gazillion const strings making
the difference relevant though...

Rgds
Sh
Aug 24 '06 #7

Schraalhans Keukenmeester wrote:
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");

When in doubt of relative speed of alternatives, you could put both
solutions to the test.
[snip]
1 mln runs with printf() // 8 char string (or 9, including \n)
time ( ./a.out &/dev/null )
real 0m1.214s
user 0m1.207s
sys 0m0.006s

1 mln runs with puts() // 8 char string
time ( ./a.out &/dev/null )
real 0m0.552s
user 0m0.546s
sys 0m0.004s

So puts() is substantially faster in this case. With longer strings the
relative difference increases.

I wonder how often one has to output a gazillion const strings making
the difference relevant though...
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.

Aug 24 '06 #8
jaapsch wrote:
Schraalhans Keukenmeester wrote:
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");
When in doubt of relative speed of alternatives, you could put both
solutions to the test.
[snip]
1 mln runs with printf() // 8 char string (or 9, including \n)
time ( ./a.out &/dev/null )
real 0m1.214s
user 0m1.207s
sys 0m0.006s

1 mln runs with puts() // 8 char string
time ( ./a.out &/dev/null )
real 0m0.552s
user 0m0.546s
sys 0m0.004s

So puts() is substantially faster in this case. With longer strings the
relative difference increases.

I wonder how often one has to output a gazillion const strings making
the difference relevant though...

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 %.

Robert Gamble

Aug 24 '06 #9
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.

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!").

Standardized benchmarks can be helpful measurement tools,
but they're rotten policy drivers.

--
Eric Sosman
es*****@acm-dot-org.invalid
Aug 24 '06 #10

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

Similar topics

24
5869
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
17463
by: infobahn | last post by:
printf("%p\n", (void *)0); /* UB, or not? Please explain your answer. */
4
1850
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
15499
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
5605
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
2862
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
2681
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
18054
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
6866
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
9698
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
9558
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10298
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
9105
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
7594
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
6833
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5489
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
4265
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
3785
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.