Which is quicker between printf %s and for loop %c [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Please I'd like to know which is better/quicker to process between:
printf("%s", foo);
and
for(int i = 0; i < len; i++)
printf('%c', foo[i]);`
I have noticed that the output is not always the same.

The single call printf("%s", foo); is most likely faster. You only make one function call to printf instead of n function calls, each of which has to parse the format string.
Even if the latter was faster, the former is still preferred because it is clearer to the reader.

Performance test it. Trying to come up with any rule that A is faster than B is bad practice. The assumption will become incorrect over time or in slightly different scenarios. Always performance test when optimizing.
Write a test case and test it with a high precision timer. Make sure your performance timer has a high enough granularity to show differences. On Windows you can use QueryPerformanceCounter. Googling that function should get you started.

Note that there is a syntax error in: for(int i = 0; i < len; i++) printf('%c', foo[i]);. It should read:
int len = strlen(foo);
for (int i = 0; i < len; i++)
printf("%c", foo[i]);
This loop, assuming the length of foo fits in a int, is quite inefficient. printf("%s", foo); is very likely faster than that, but if you have noticed different output, there is something fishy going on... Maybe len was not computed properly.
Note also that you could write a potentially more efficient version:
for (int i = 0; i < len; i++)
putchar(foo[i]);
And you could also improve on printf("%s",foo); with this variant:
fputs(foo, stdout);
But as always, you should test and benchmark on your system to measure actual performance. Some compilers will optimize the printf("%s", foo); into fputs(foo, stdout); automatically.

The statement without loop is probably faster than the statement with loop.
Using for loop
for(int i = 0; i < len ; i++)
printf("%c", foo[i]) ;
In every iteration, i is compared with 'len' and i is incremented after every character is printed.
Without loop
printf("%s", foo) ;
foo here is basically a pointer to string and it will go on printing every character after foo[0] until a '\0' character (or terminating character) is found.
So, in the 2nd case, we save the time to update i and access foo[i] with respect to foo[0].
To add a disclaimer, the actual performance testing might lead you to results that would depend on the compiler and the operating system you are working on.

Related

Why does this C code take so long to compile and execute if the variable is not initialized? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
The following C code takes so long to compile and execute.
#include <stdio.h>
int main()
{
int max;
printf("Enter a value for max: ");
scanf("%d", &max);
for (int i=0; i<max; i++)
{
printf("%d\t", i);
}
return 0;
}
But, If I initialize the max variable with some number like
int max = 0;
The Compilation and execution is almost instantaneous. Can someone explain why?
Edit:
When I printed the value of the variable max before my input, it showed 2203648 (some garbage value). Instead of "int max = 0", if i assign
int max = 2203648;
the compilation and execution takes the same long time. But, as mentioned earlier, if i assign max say
int max = 200;
the compilation and execution is instantaneous. Does it have to do anything with the pre-assigned garbage value?
Also, this problem occurs only in windows computers, I tested with ubuntu, and the compilation and execution is instantaneous in both version of the code.
In Windows 10:
compilation and execution, as of "Enter a value for max: " appears on screen:
without variable initialization = around 8 seconds
with variable initialization = instantaneous
compiler - gcc
The scanf is failing. Check the return value.
i.e.
if (scanf("%d", &max) != 1) {
fprintf(stderr, "Unable to read max");
exit(1);
}
max is probably some large value hence the large amount of time
EDIT
The delay to see the prompt is that the printf is in a buffer and will not be displayed until the loop completes
I think variable initialization of max=0 doesn't make that great deal of a difference, but god knows why in ypur case its taking 8seconds. I think you should reinstall your GCC Compiler set your path variables correctly once more, and try the above code on a different IDE.

C programming - Finding the necessary number in the array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
The task is to calculate how many times a certain digit occurs in the entered sequence of numbers. The number of numbers to be entered and the number to be calculated are set by typing. Ask me if you have got question about code. The problem in finding a match with the number entered in the array.Can you give me hints or instructions, also i think about loop while but i don't know how to realize it please
The code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, b, n, c=0, arr[30];
printf("The count of numbers: ");
scanf("%d", &n);
printf("The number what is finding: ");
scanf("%d", &b);
for (i = 0; i < n; ++i)
{
scanf("%d", &arr[i]);
}
for(i=0;i < n;i++)
{
if(arr[i]=b)
{
c++;
printf("%d", c);
}
}
}
You should be compiling your code with at least some basic compilation flags. If you do, you will get a heads up that something is wrong before having to run it to find out. It saves a lot of time in the long run. Consult your compiler's documentation.
For instance, it would point out that your if condition is using an assignment (=) instead of an equality comparison (==). It should be:
if (arr[i] == b)
Also, you probably want to print out the total count at the end of the program - after the loop is finished. So move the printf("%d\n", c); after the loop. (You were also missing a newline which you probably wanted).
Also, scanf has a return value - you should check it. If the user enters invalid integers, you want to catch that and handle it properly.
Finally, since you declare your array to be of size 30, you should add a check that the desired length of the input array is no longer than that -- otherwise, you would get a buffer overflow.
Side note: please use more descriptive variable names. Not doing so often leads to confusion, especially for beginners. A small exception to this is for loop counters, like i in this case -- its perfectly fine to use a single letter. But consider b -- there is no obvious meaning; it should be something like target or to_find. Also, c could be count or total. As for n, perhaps size or length would be more suited.
if(arr[i]=b) it's wrong. x = y is an assignment but you want to do a check. To check if two elements are equal you should write if(arr[i] == b).

sizeof vs strlen in long running programs [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Which of these is faster and can be used in programs which runs 100s of times in a loop (for size of strings)?
sizeof - it is a macro and a compile time expression.
or
strlen - it's run time expression.
In my mind I want to avoid strlen as it's a function and calling it again and again might slow things down - Am I correct?
These do not do the same thing.
sizeof is an operator which, in most cases, is evaluated at compile time. It gives the size in bytes of a variable, including arrays and structs. In contrast, strlen is a function which returns the length of the string passed to it.
For example:
char str[100] = "hello";
printf("size = %zu\n", sizeof str); // prints 100
printf("len = %zu\n", strlen(str)); // prints 5
That being said, if you're looking to optimize something like this:
int i;
for (i=0; i<strlen(str); i++) {
...
}
You should do this instead:
int i;
int len = strlen(str);
for (i=0; i<len; i++) {
...
}
If your strings are not string literals or arrays then strlen is your only choice. Either way, it will be fast—strlen is usually very heavily optimized.

For looping in C confused [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
What problem if I use strlen() in the condtion of for loop.
char s[i];
for (int i = 0; strlen(s); i++)
So if I use upper code there took a lot of time.
But if I store the value of strlen of s it took little time inspect to upper code.
What difference between these?
You should not use i < strlen(s) as a condition because the length of the string in s gets recomputed for each iteration of the loop. It is better to use a separate variable and compute the length in the initialization part:
for (size_t i = 0, len = strlen(s); i < len; i++) {
...
}
Note that your definition of s looks like a typo: char s[i];. What variable i are you referring to? what would be its value before the beginning of the for loop that defines a new i variable?
EDIT
After reformatting your code, I realized there is even more confusion:
for (int i = 0; strlen(s); i++)
This for loops iterates as long as string s is not empty. Is this your intent? Do you modify s inside the loop? s is uninitialized, the test invokes undefined behavior. Do you initialize s in code you did not post between the definition and the for loop? If you do, it would still be more efficient to write such a loop this way:
for (int i = 0; *s != '\0'; i++)
The condition is evaluated before every iteration of the loop.
C strings are just an array of characters, then a NULL. So to work out the length you have to start at the start and inspect every character from there until you find the NULL.
So in complexity terms, strlen is O(n). Your for is also O(n). If you check the strlen every time then your implementation is O(n*n). If you work it out once in adavance then yours os O(n). Try it with longer ss to see a much bigger difference.

print the changed variable before the calculation is done [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
in a c program, i want the variable 'count' to be printed at the beginning of the program. But the calculation for the value of 'count' is done later. How do you accomplish this?
count = 0;
printf("the value of count is : %d", count);
count = 20;
I know in this case, the output is 0. But I need 20 to be printed.
The idea of program flow is that commands are executed in a certain order. You don't expect the waiter to bring you your meal before you have told him what you want to eat - but that seems to be what you are asking.
Of course the order of lines in a file is not necessarily the order of execution: you have have a line "at the start of the file" that is executed later: for example
#include <stdio.h>
// we define the print statement here:
void printCount(count) {
printf("the count is now %d\n", count);
}
int main(void) {
int count = 20;
printCount(count); // but we don't execute it until we get here...
return 0;
}
Now your "print" statement occurs (in the file) before you assign (calculate) count - but of course they are being executed in the correct order.
afterthought
If it's a case of printing "the number of cases is n", you could of course do
printf("the number of cases is ");
cases = 5; // whatever math is needed happens here...
printf("%d\n", cases);
and the result is
the number of cases is 5
just as you wanted... this works because there was no carriage return after printing "the number of cases is" - so the number follows when you have figured it out.
edit
Reading through the question and comments one more time I think I understand what your issue is. You have a loop that counts a number of inputs (say the number of lines in a file) and want to print both the total number of cases (not known before the loop) and something about each case (discovered during the loop) but without having to loop over all the data twice. There is a way to do this, using a print buffer. If data access is really slow and looping twice would be prohibitive, this might be an option. You would want to initialize a "sufficiently large" print buffer in memory and use snprintfto create the string you need. In reality you will "loop over" the bytes in the output string twice but there is minimal performance penalty (compared to everything else). Incomplete example:
int count=0,num, sofar=0;
char buf[2000];
// assume file is opened and handle is fp
while(true){
if (fscanf(fp, "%d", &num) <1) break;
sofar+=snprintf(buf+sofar, "%d\n", 2*num); // some "math" on number for each "case"...
count++;
}
printf("There were %d lines\n", count);
printf("Here they are multiplied by two:\n");
printf("%s\n", buf);
Obviously the above is incomplete - you need to check for errors, open/close the file, etc - I am just trying to point out the principle - this way you only loop through the data (file) once but print the count before the contents.
you can't print 20. how can you print a variable before its get initialized?

Resources