0

I'm working on a little school project to re-code the SpaceInvaders Game, without using ncurses, but only the basic libraries, and i want to use time to print my screen-buffer every time, so i need to know when to print exactly so the user won't feel the screen lagging.

I started using the Clock_t structure as a test like :

clock_t stime = clock();
sleep(3);
clock_t etime = clock();
unsigned long millis = ((etime - stime) * 1000) / CLOCKS_PER_SEC;
printf("%lu\n",millis);

but the output is 0 all the time, i want know why and how i can fix it so i can see milliseconds, or nanoseconds

Mat
  • 202,337
  • 40
  • 393
  • 406
  • Use a `float` or `double` instead. your result is going to be 0 < r < 1 so it'll be a floating point value. Using a `long` is probably truncating the decimals – m_callens Apr 06 '17 at 14:37
  • 1
    http://stackoverflow.com/questions/1083142/what-s-the-correct-way-to-use-printf-to-print-a-clock-t – Jean-François Fabre Apr 06 '17 at 14:39
  • 1) there is no type `Clock_t` 2) `clock_t` is not a structure. – too honest for this site Apr 06 '17 at 14:54
  • @SergeBallesta Code is printing a `unsigned long`, not a `clock_t`. Disagree that the answer in the link applies. – chux - Reinstate Monica Apr 06 '17 at 18:26
  • For investigation, print out the clock values. `printf("%e %e %e\n", (double)stime, (double)etime, (double)CLOCKS_PER_SEC);` I suspect `sleep()` is not sleeping 3 seconds. – chux - Reinstate Monica Apr 06 '17 at 18:28
  • `clock_t stime = clock(); sleep(3); clock_t etime = clock(); printf("%e %e %e\n", (double)stime, (double)etime, (double)CLOCKS_PER_SEC); double millis = (double)((etime - stime) * 1000) / CLOCKS_PER_SEC; printf("%lf\n",(double)millis);` and the output is `6.410000e+02 8.020000e+02 1.000000e+06 0.161000` –  Apr 06 '17 at 22:25

1 Answers1

0

Add some print statements to your code:

clock_t stime = clock();
sleep(3);
clock_t etime = clock();
// print etime and stime and (etime - stime) * 1000 and CLOCKS_PER_SEC
unsigned long millis = ((etime - stime) * 1000) / CLOCKS_PER_SEC;
printf("%lu\n",millis);

You will see that the numerator is smaller than the denominator in your expression, therefore since you are using integer math you will truncate the result and it will be zero

nicomp
  • 4,344
  • 4
  • 27
  • 60