Reputation:
having learnt that,
printf("%*s", 10, "");
is same as
printf("%10s", "");
Which of these is faster, efficient and more compiler-friendly?
Upvotes: 0
Views: 222
Reputation: 790
You can always check the result by coding.
#include<stdio.h>
#include<time.h>
using namespace std;
int main()
{
double cl = clock();
for(int i=0;i<100000;i++){
printf("%*s", 10, "");//3.814
}
cl = clock() - cl;
fprintf( stderr, "%lf\n", cl / CLOCKS_PER_SEC );
//printf("%10s", "");//3.617
return 0;
}
time limit in my pc is being commented. This can differ in different pc. But i think your ans is given;
Upvotes: 0
Reputation: 70391
Which one is faster depends on implementation details of the library. The "%*s"
variant pulls an additional parameter from the stack... I would expect the difference to be marginal, especially compared to the overhead cost of terminal output.
If you need the output width to be variable, use "%*s"
. If you don't, go for the simpler "%10s"
, which is (IMHO) more legible.
Upvotes: 1
Reputation: 263637
printf("%*s", 10, "");
That will print 10 spaces.
printf("%10s", 10, "");
That's incorrect; surely you meant:
printf("%10s", "");
which will also print 10 spaces.
I honestly don't know which one is faster, and it could depend on the particular printf
implementation. The first version has to process an additional argument. In the second, printf
is given an int
value which it doesn't have to parse from the character sequence '1'
,'0'
.
But I'm reasonably confident that any difference in performance is likely to be insignificant compared to the cost of writing those 10 bytes of data to an output device, whether it's a terminal window (rendering each pixel of the chosen font's representation of the space character onto the display), to a file on disk (waiting for the read-write head to move into position and for the platter to rotate to the point where you want to write, though much of that is likely done in parallel), or to a network connection (you get the idea).
There are cases where performance difference are important. Don't call strlen()
on each iteration of a loop if you can call it once and store the result. Don't use Bubblesort for a large array when you can use Quicksort -- or just call qsort()
, which will have been optimized to within an inch of its life.
This is not one of those cases.
Instead, write whatever most clearly expresses your intent. If I know I want exactly 10 spaces, I'll probably write printf("%10s", "");
; if the number of spaces is determined at run time, I might write printf("%*s", n, "");
.
And if you write simpler code, you'll have a better shot at getting it right the first time; imagine how many more CPU cycles you'll use up fixing and recompiling your program.
As for which is more "compiler-friendly", I'm not sure what you mean by that. The compiler won't be offended if you give it work to do.
Upvotes: 6