Reputation: 217
I've been given two sets of C code and I've been asked to use this code:
#include <stdio.h>
void main() {
int n, c=0;
scanf("%d", &n);
while(n != 1) {
c++;
if(n%2 == 0)
n = n/2;
else
n = 3*n + 1;
}
printf("n = %d\n", n);
printf("iterations = %d\n", c);
}
Then I have to use this code to add a time stamp to the program above after the input statement and before the end of the program. I have to use this to calculate the number of clock cycles and seconds it takes for the program to execute.
#include <stdio.h>
#include <time.h>
void sleep2(int wait) {
clock_t goal; // clock_t defined in <time.h>
goal = wait * CLOCKS_PER_SEC + clock();
while( goal > clock() )
;
}
main() {
int delay;
printf("Enter an integer ...\n");
scanf("%d", &delay);
printf("To be delayed for %d seconds ...\n", delay);
sleep2(delay);
printf("expired\n");
}
I feel like this should be simple, but I'm not sure how to use the code to put in a time stamp. Could someone help me with the code or just get me started?
Thanks!
Upvotes: 2
Views: 3141
Reputation: 5786
If it only has to be accurate to the second use time.h. Then you could do something like:
time_t startT = time(null);
//stuff
time_t finalTime = time(null) - startT;
If you need more accuracy see this post: https://stackoverflow.com/a/275231/1153203
Upvotes: 2
Reputation: 20664
Basically do this:
clock_t start;
clock_t elapsed;
start = clock();
...
elapsed = clock() - start;
elapsed
will be the elapsed time in 'ticks', where there are CLOCKS_PER_SEC
ticks per second.
Upvotes: 1