2

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!

jam
  • 3,640
  • 5
  • 34
  • 50
aclark
  • 219
  • 1
  • 4
  • 13
  • Welcome to StackOverflow. Please take a few seconds to properly format your code when posting. You can preview it realtime when writing it in the area just below where it's being written to check. Hints: Use spaces instead of tabs, and start the main body of your code by indenting 4 spaces. Formatting it properly makes it easier for people to read (and other's don't have to spend their time doing it) :), and the easier your question is to read the more likely it is you'll get an answer. (And more quickly, too.) Thanks. :) – Ken White Jan 20 '12 at 01:47
  • That's a confusing second program you've got there. It just [busy-waits](http://en.wikipedia.org/wiki/Busy_wait) until a certain amount of time has _passed_. It is useless for telling you how long something actually took. (Though the `clock()` function could definitely provide that.) – sarnold Jan 20 '12 at 01:51
  • @KenWhite - Sorry about that. I did use spaces instead of tabs but I guess it still didn't work. – aclark Jan 23 '12 at 04:14
  • @sarnold - Yes, see that's what I thought the second program did too. But that's what the instructor's directions were, so that's why I was sort of confused. Thanks. – aclark Jan 23 '12 at 04:17

2 Answers2

2

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

Community
  • 1
  • 1
Sean Dawson
  • 5,587
  • 2
  • 27
  • 34
1

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.

MRAB
  • 20,356
  • 6
  • 40
  • 33