Archive for September 2011
How to calculate the time required for a block of code in C/C++?
Here are a small code snippets with which you can calculate the execution time of a certain block of codes in C/C++.
#include <stdio.h> #include <time.h> #include <stdlib.h> clock_t startm, stopm; #define START if ( (startm = clock()) == -1) {printf("Error calling clock");exit(1);} #define STOP if ( (stopm = clock()) == -1) {printf("Error calling clock");exit(1);} #define PRINTTIME printf( "%6.3f seconds used by the processor.", ((double)stopm-startm)/CLOCKS_PER_SEC); int main() { START;//start the timer //code blocks which execution time will be counted begins here int n; for(n = 0; n<=65535; n++) { printf("%d\n", n); } //code blocks which execution time will be counted ends here STOP;//end the timer PRINTTIME;//print the time return 0; }
The program will print total 65536 numbers line by line and at the end it’ll print the total seconds e.g 5.109 seconds, it took to print the numbers
—–courtesy: http://kennethfinnegan.blogspot.com/2008/03/timing-events-in-c.html
Basic Programming Quiz 0010
Examine the code snippets given below—-
#include <stdio.h> int main() { char ch; while((ch = getchar()) != '\0') putchar(ch); return 0; }
What does the program display?
Look at another code snippets—-
#include <stdio.h> int main() { while( putchar(getchar( )) != '\0' ) ; return 0; }
Now, what does it display?
Is there any difference in program execution between these two code snippets?
Basic Programming Quiz 0001
Examine the code snippets given below—-
#include <stdio.h> int main() { int x; x = 10; if(x == 10) { int x; x = 99; printf("Inner x: %d\n", x); } printf("Outer x: %d\n", x); return 0; }
What does the program displays?