Which one takes less Execution time and why? [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
1.
int main() { int a; a = 0; }
//OR
2.
#define ZERO 0 int main() { int a; a = ZERO; }
I think that the second one takes less execution time because it is preprocesssed.

The one liner - compilation time and execution time are different metrics altogether!!
Any program, written in mid to high level language, is not executed as-is by the system. For C, it is the compiler, which takes the source file as input and produces the binary (machine-executable code). In the process, it incorporates a lot of optimization to the code.
In this case, it's most likely, that the compiler will optimize out the statements altogether, as they are not used meaningfully. Both the snippets are likely to generate the same binary (unless you forcefully turn off the optimization). If at all, you have to check the generated binary and perform the time-measurement to check the final result.

They are equal. The compiler's preprocessor just replaces ZERO before doing anything.
Assuming it is written like this:
#define ZERO 0
int main() { int a; a = ZERO; }
The program will be transformed to
int main() { int a; a = 0; }
before it is compiled and it will not reach optimization step.
Update:
Just to clarify, sometimes you see codes like this:
#define ERROR_MEMORY_ALLOCATION_FAILED -1
char *buf = malloc(10);
if (!buf)
return ERROR_MEMORY_ALLOCATION_FAILED;
This can help code readability a lot, especially when you reuse these definitions.

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.

Code output explanation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Question 1.
#include <stdio.h>
int main(void)
{
int c;
while((c=getchar())!='\0')
{
putchar(c);
}
}
Input
Hello C.
Tell me about you.
Output
Hello C.
Tell me about you.
ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ
and it continues with status-time limit exceeded.
Question 2.
#include <stdio.h>
int main(void)
{
float a;
a=46.43253;
printf("\n%d",a);
printf("\n%f",a);
return 0;
}
Output
536870912
46.432529
Output- 536870912
46.432529
In general using incorrect format specifier triggers undefined behavior - which is what you have when you use %d in printf for printing float. In this case, you can expect any output usually.
However, it may also be the case that since you have specified to read the float number as integer (e.g. by using %d specifier), it simply interpreted the result as integer - hence the strange number (since floats and integers are stored differently).
If you are interested why the second printf prints a number slightly different from yours, this may help you.
This block is fine:
float a;
a=46.43253;
This block is also fine:
printf("\n%f",a);
The problem is with this block:
printf("\n%d",a);
Particularly this part:
"\n%d"
Please keep in mind you declared a float and using the integer syntax to output it. That's why you are getting the negative output
If it is a case where you don't want to change the "%d," then simply cast it as a float before output

Display the progress of completion while the program is being executed [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to display the progress of my C program in percentages while it is running. The actual work in the program whose progress should be measured is confined in a loop. Here is what I tried:
int i;
int to = 100000000;
while (i++ < to) {
printf("\rPercent done: %d", (100 * i)/to);
}
Might be a dumb question, but how does one display a progress while
the program is running?
Not like this.
You have multiple issues:
Your i is uninitialized, so the program will print garbage. (Fix: -> int i = 0; instead)
Your "progress counter" will only count the progress while in the loop. As soon as Percent done: 100 will be printed, only the loop will be over.
You're printing 100 million lines to the console. Maybe think that through again.
With (i*100)/to you're hitting integer overflow about half way through, so use i / (to / 100) instead. Notice depending on the compiler the compiler could optimize that out by itself.
A little less obnoxious way would be:
#include <stdio.h>
int main (void) {
int i = 0;
int to = 100000000;
while (i++ < to) {
if (i % 1000000 == 0) {
printf("\rPercent done: %d", i / (to / 100));
}
dostuff();
}
printf("\rLoop finished");
return 0;
}
Note that this will only accurately reflect how far the program has come executing the loop. Any work before/after the loop will not be measured by this.
This only prints a console message for every full percent. Still obnoxious that you're getting 100 console messages, but nowhere near as bad as 100.000.000 (!) calls to printf. Still though, that's still a performance impact.

Is it possible to do the Kattis "Mixed Fractions Q" in C and under the 2 second limit [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Basically i've attempted to answer this question from Kattis:
https://open.kattis.com/problems/mixedfractions
I have a working solution however it goes over the allocated 2 second time limit for computation. My question is essentially, is it even possible to write a solution to this problem in the C programming language that can compute the maximum input in under 2 seconds.
When reading through the other statistics "problems/mixedfractions/statistics" I've noticed that nobody else has used C or similar procedural languages. The feedback just says it went over the time limit but I'm not sure if that's because C can't do the calculation fast enough or if I've made a mistake in my code.
Thanks for the help, I'll chuck my code in below for reference!
http://pastebin.com/7EtA2d3S
EDIT: Thanks for the response to the question, as you can see I'm new to the SO scene and to C (well programming in general) and was just trying to practice, sorry if my code was dreadful. Basically to clarify all I was trying to ask was if this particular question is possible in C (because nobody else had done it in C), thanks again and I'll try and get this post removed so not to waste anyone else's time.
I can't imagine how your code remotely managed to exceed 2s runtime on the three samples given.
The version I just knocked up runs so fast it doesn't register any time at all:
#include <stdio.h>
int main(int argc, char *argv[])
{
while (1) {
unsigned int a, b;
unsigned int c, d, e;
scanf("%u %u", &a, &b);
if (a == 0 && b == 0) break;
c = a / b;
d = a % b;
e = b;
printf("%u %u / %u\n", c, d, e);
}
}
Running:
% /usr/bin/time ./mixed < data.in > data.out
0.00 real 0.00 user 0.00 sys
EDIT Ah, I see - Kattis has its own runtime environment, and supplies larger data sets than the sample shown on the page. My time on Kattis itself was 0.04s - not fantastic, but not horrendous either. Using the div(n, d) function that calculates the remainder and quotient in one step is faster.

Project euler number 10 in C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
i cant get the following code to run, ie it dosent give out any output
the objective is to find the sum of all primes below 2 million,
#include <stdio.h>
#include <math.h>
int is_prime(long long int i)
{
long long int n;
if(i==2)
return 1;
for(n=2;n<=sqrt(i);n++)
if(i%n==0)
return 0;
return 1;
}
int main()
{
long long int s=0,i=2;
for(i<2000000;i++;)
{
if(is_prime(i))
s=s+i;
}
printf("sum: %lli",s);
return 0;
}
You're using the for loop wrong. A for loop looks like this:
for(initialization; test expression; update)
But you wrote
for(i<2000000;i++;)
which should be
for(;i<2000000;i++)
ie, skip initialization, on each iteration test for i<2000000 and increment.
Your problem is that you are essentially factorising every integer up to two million for this. It's not that your code isn't working, it just is running very very slowly. If you attach a debugger to it you will most likely be at line
if(i%n==0)
most of the time.
Implement the Sieve of Eratostenes. Will be the most effective here.
Also your loop for(i<2000000;i++;) will run for 2^64 cycles.

Resources