C++ 延迟执行1秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9616957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:04:34  来源:igfitidea点击:

Delay execution 1 second

c++delaysleep

提问by raze

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

所以我正在尝试编写一个简单的基于刻度的游戏。我在 linux 机器上用 C++ 编写。下面的代码说明了我要完成的任务。

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

Well, this doesn't work. It seems that it sleeps for 40 seconds, then prints out whatever the result is from the function call.

嗯,这行不通。它似乎休眠了 40 秒,然后打印出函数调用的任何结果。

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

我还尝试创建一个名为 delay 的新函数,它看起来像这样:

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

    time(&start);

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

Same result here. Anybody?

这里的结果相同。有人吗?

回答by Alex Z

To reiterate on what has already been stated by others with a concrete example:

用一个具体的例子重申其他人已经说过的内容:

Assuming you're using std::coutfor output, you should call std::cout.flush();right before the sleep command. See this MS knowledgebase article.

假设您使用的std::cout是输出,您应该std::cout.flush();在 sleep 命令之前调用。请参阅此 MS 知识库文章。

回答by Frank Schmitt

sleep(n) waits for n seconds, not n microseconds. Also, as mentioned by Bart, if you're writing to stdout, you should flush the stream after each write - otherwise, you won't see anything until the buffer is flushed.

sleep(n) 等待 n 秒,而不是 n 微秒。此外,正如 Bart 所提到的,如果您要写入 stdout,则应在每次写入后刷新流 - 否则,在刷新缓冲区之前您将看不到任何内容。

回答by jfs

So I am trying to program a simple tick-based game. I write in C++ on a linux machine.

所以我正在尝试编写一个简单的基于刻度的游戏。我在 linux 机器上用 C++ 编写。

if functioncall()may take a considerable time then your ticks won't be equal if you sleep the same amount of time.

如果functioncall()可能需要相当长的时间,那么如果您睡眠相同的时间,您的滴答声将不相等。

You might be trying to do this:

您可能正在尝试这样做:

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

Here tick()sleeps approximately delay - time_it_takes_for(functioncall)i.e., the longer functioncall()takes the less time tick()sleeps.

这里tick()睡眠大约,delay - time_it_takes_for(functioncall)即,睡眠时间越长functioncall()tick()睡眠时间越短。

sleep()sleeps an integer number of seconds. You might need a finer time resolution. You could use clock_nanosleep()for that.

sleep()休眠整数秒。您可能需要更精细的时间分辨率。你可以用clock_nanosleep()它。

Example Clock::tick() implementation

示例 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
  }
}

Note: I've used std::flush()to update the output immediately.

注意:我习惯于std::flush()立即更新输出。

If you run the program it should take about 5 seconds (100 frames, 20 frames per second).

如果您运行该程序,它应该需要大约 5 秒(100 帧,每秒 20 帧)。

回答by Rohit Vipin Mathews

I guess on linux u have to use usleep()and it must be found in ctime

我想在 linux 上你必须使用usleep()它,它必须在ctime

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

在 Windows 中你可以使用 delay()、sleep()、msleep()