u185619
u185619

Reputation: 287

a function that is faster than printf

I am beginner c programmer and I read that printf() is very sophisticates function that is very slow and consumes many CPU cycles. So I want to know is there any function that exists in standard pure c library and is faster than printf() or not and when to use that function and when not to use it. My goal is to write efficient code that can work on any computer and/or embedded system

Upvotes: 0

Views: 7120

Answers (2)

user3528438
user3528438

Reputation: 2817

There are a reasons that discourages the use of printf.

1) printf is a function and is not likely to be inline-able, so as a function it disrupts the compiler optimization of the code around it. If you have a loop that does a lot of heavy lifting and you want compiler to do a good job optimizing it, then don't call any non-inlined function inside that loop.

2) The way stdio route out the content is very implementation dependent, and can be very slow. If you are using a development board to run the code, then stdio is usually implemented via JTAG. In this case, not only printf but everything through stdio are extremely slow. If you use printf too much, you'll hit the timing limit easily.

3) Your target platform may not implement stdio. This is common for embedded platform, because they are EMBEDDED in something else and might not have an easy way to route contents in or out.

And to your question: yes and no.

Yes: there are, trace utilities that are designed to be lightweight and fast and can be used as a faster alternative to printf, like GT_TRACE by Texas Instruments for their DPS's. Unlike printf, trace can be easily turned off at run time and compile time. When turned off, they take very little time.

No: trace utilities are not standard C. They are usually part of your target platform's SDK

Bottom line: for now, don't think too much about it. Replace printfs with trace when you move to embedded platform, if necessary.

Upvotes: 1

u185619
u185619

Reputation: 287

actually I found that write() is the fastest alternative to printf() I have written 2 little programs that prints hello world to standard out the first one

#include <stdio.h>
#include <string.h>
#include <unistd.h> int main() {
char* h = "hello world\n";
for ( int i=0; i < 100000; i++) write(0,h,strlen(h));
}

and the second one

#include <stdio.h> 
int main() {
char* x = "hello world\n";
for (int i =0;i<100000; i++) printf("%s",x); }

and compared the run time of the 2 programs on my pc computer the first terminated in 2.740s while the second terminated in 3.071s

Upvotes: 5

Related Questions