Delay 1 second

So, I'm trying to program a simple tick-based game. I am writing in C ++ on a Linux machine. The code below illustrates what I'm trying to accomplish.

for (unsigned int i = 0; i < 40; ++i)
{
    functioncall();
    sleep(1000); // wait 1 second for the next function call
}

Well, that doesn't work. It seems that he sleeps for 40 seconds and then prints regardless of the result of the function call.

I also tried to create a new function called delay, and it looked like this:

void delay(int seconds)
{
    time_t start, current;

    time(&start);

    do
    {
        time(&current);
    }
    while ((current - start) < seconds);
}

The same result. Is anyone

+5
source share
4 answers

Repeat what has been said by others with a concrete example:

Assuming what you use std::coutfor output, you should call std::cout.flush();right before the sleep command. See this MS Knowledge Base article.

+6
source

sleep (n) n , n . , , stdout, - , .

+4

, . ++ Linux-.

functioncall() , , .

, :

while 1: // mainloop
   functioncall()
   tick() # wait for the next tick

tick() delay - time_it_takes_for(functioncall), .. functioncall() tick().

sleep() . , . clock_nanosleep() .

Clock:: tick()

// $ g++ *.cpp -lrt && time ./a.out
#include <iostream>
#include <stdio.h>        // perror()
#include <stdlib.h>        // ldiv()
#include <time.h>        // clock_nanosleep()

namespace {
  class Clock {
    const long delay_nanoseconds;
    bool running;
    struct timespec time;
    const clockid_t clock_id;

  public:
    explicit Clock(unsigned fps) :  // specify frames per second
      delay_nanoseconds(1e9/fps), running(false), time(),
      clock_id(CLOCK_MONOTONIC) {}

    void tick() {
      if (clock_nanosleep(clock_id, TIMER_ABSTIME, nexttick(), 0)) {
        // interrupted by a signal handler or an error
        perror("clock_nanosleep");
        exit(EXIT_FAILURE);
      }
    }
  private:
    struct timespec* nexttick() {
      if (not running) { // initialize `time`
        running = true;
        if (clock_gettime(clock_id, &time)) {
          //process errors
          perror("clock_gettime");
          exit(EXIT_FAILURE);
        }
      }
      // increment `time`
      // time += delay_nanoseconds
      ldiv_t q = ldiv(time.tv_nsec + delay_nanoseconds, 1000000000);
      time.tv_sec  += q.quot;
      time.tv_nsec = q.rem;
      return &time;
    }
  };
}

int main() {
  Clock clock(20);
  char arrows[] = "\\|/-";
  for (int nframe = 0; nframe < 100; ++nframe) { // mainloop
    // process a single frame
    std::cout << arrows[nframe % (sizeof(arrows)-1)] << '\r' << std::flush;
    clock.tick(); // wait for the next tick
  }
}

. std::flush() .

, 5 (100 , 20 ).

+2

I assume linux should use usleep(), and it needs to be found inctime

And in windows you can use delay (), sleep (), msleep ()

0
source

All Articles