Home > Blockchain >  Only updating the displayed time elapsed when the time change in C
Only updating the displayed time elapsed when the time change in C

Time:06-08

I would like to display the seconds elapsed after the start of program:

  volatile time_t start_time = time(NULL);
  volatile time_t target_seconds = 60*60*17;
  volatile time_t time_passed = 0;
  while(1)
  {
        time_passed = time(NULL)-start_time;
        printf("\rTime elapsed=%lu/%lu(seconds)", time_passed, target_seconds);
  }

Output:

Time elapsed=1/61200(second)

But it will keep updating the display no matter what value time_passed is.

Now I only want to update the displaying time elapsed when the actual time is incremented. So I changed the program in this way:

  volatile time_t start_time = time(NULL);
  volatile time_t target_seconds = 60*60*17;
  volatile time_t time_passed = 0;
  while(1){
      if ((time(NULL)-start_time) != time_passed)
      {
        time_passed = time(NULL)-start_time;
        printf("\rTime elapsed=%lu/%lu(seconds)", time_passed, target_seconds);
      }
    }

Now it displays nothing. Can anyone explain why and how to solve it.

CodePudding user response:

Your code is fine.

But depending on your platform the output buffer is flushed only when a \n is printed.

Therefore you should add fflush(stdout); right after the printf.

    if ((time(NULL)-start_time) != time_passed)
    {
      time_passed = time(NULL)-start_time;
      printf("\rTime elapsed=%lu/%lu(seconds)", time_passed, target_seconds);
      fflush(stdout);
    }

BTW: if you wait long enough, you'll end up seeing some output because eventually the output buffer will be full and then everything will be displayed at once, which of course doesn't make much sense here.

The reason why you see immediately output with the first version of your code is that your're printing contiuously and therefore the output buffer will be full very quickly, and it will be flushed contiuously hence you see output.

The volatile keyword is not required here, it's absolutely unnecessary but it doesn't harm either.

CodePudding user response:

Apart from calling fflush after every printf it's also possible to turn off buffering on stdout. use either setbuf or setvbuf

#include <stdio.h>

setbuf(stdout, NULL);
    
setvbuf(stdout, NULL, _IONBF, 0); 

Now every character will get printed

  •  Tags:  
  • c
  • Related