6

我对 C++ 比较陌生,所以我没有大量的经验。我已经学习了 Python,并且正在尝试制作我用 C++ 编写的 Python 代码的改进版本。但是,我希望它实时工作,所以我需要设置 While 循环的速度。我确定有答案,但我找不到。我想要一个与此类似的代码:

rate(timeModifier * (1/dt))

这是我在 Python 中使用的代码。我可以设置一个变量 dt 来使计算更精确,而 timeModifier 可以将速度提高一倍或三倍(1 将其设置为实时)。这意味着程序将每秒循环 1/dt 次。我知道我可以在标题中包含 time.h,但我想我对 C++ 太陌生了,无法理解如何将其转移到我的需求中。

4

6 回答 6

7

您可以编写自己的计时器类:

#include <ctime>

class Timer {
    private:
        unsigned long startTime;
    public:
        void start() {
            startTime = clock();
        }

        unsigned long elapsedTime() {
            return ((unsigned long) clock() - startTime) / CLOCKS_PER_SEC;
        }

        bool isTimeout(unsigned long seconds) {
            return seconds >= elapsedTime();
        }
};


int main() 
{
    unsigned long dt = 10; //in seconds
    Timer t;
    t.start();

    while(true) 
    {
        if(t.elapsedTime() < dt) 
        {
            //do something to pass time as a busy-wait or sleep
        }
        else 
        {
            //do something else
                    t = Timer(); //reset the timer
        }
    }
}

请注意,不鼓励忙等待,因为它们会占用 CPU。如果您不需要执行任何操作,请使用sleep命令 (Windows) 或usleep( Linux)。有关在 C++ 中制作计时器的更多信息,请参阅此链接

于 2012-05-18T13:39:22.817 回答
4

您不能在 C++ 中以相同的方式进行操作。Sleep您需要在计算循环、 Windows 或usleep*NIX上手动调用某种睡眠函数。

于 2012-05-18T13:42:20.667 回答
2

It's been a while since I've done something like this, but something like this will work:

#include <time.h>

time_t t2, t1 = time(NULL);

while(CONDITIONS)
{
    time_t t2 = time(NULL);
    if(difftime(t2, t1) > timeModifier)
    {
        //DO the stuff!
        t1 = time(NULL);
    }
}

I should note, however, that I'm not familiar with the precision of this method, I think it measures the difference in seconds.

If you need something more precise, use the clock() function which has the number of milliseconds since 12:00 AM beginning January 1, 1980, to the nearest 10 milliseconds. Perhaps something like this:

#include <time.h>

clock_t t2, t1 = clock();

while(CONDITIONS)
{
    t2 = clock();
    if((t2-t1) > someTimeElapsed*timeModifier)
    {
        //DO the stuff!
        t1 = clock());
    }
}

Update: You can even yield the CPU to other threads and processes by adding this after the end of the if statement:

else
{
    usleep(10000); //sleep for ten milliseconds (chosen because of precision on clock())
}
于 2012-05-18T13:43:59.030 回答
0

在 Windows 下,您可以使用QueryPerformanceCounter,同时轮询时间(例如在另一个 while 循环中)调用Sleep(0)以允许其他线程继续操作。

记住Sleep是非常不准确的。为了完全控制,只需运行一个没有操作的循环,但是您将使用 100% 的 CPU。为了减轻 CPU 的压力,您可以调用Sleep(10)等。

于 2012-05-18T14:25:49.100 回答
0

Depending on the accuracy you need, and your platform, you could use usleep This allows you to set the pause time down to microseconds:

 #include <unistd.h>

 int usleep(useconds_t useconds);

Remember that your loop will always take longer than this because of the inherent processingtime of the rest of the loop but it's a start. For anything more accurate,you'd probably need to look at timer based callbacks.

于 2012-05-18T13:42:50.737 回答
0

You should really create a new thread and have it do the timing so that it remains unaffected by the processing work done in the loop.

WARNING: Pseudo code... just to give you an idea of how to start.

Thread* tThread = CreateTimerThread(1000);
tThread->run();
while( conditionNotMet() )
{
    tThread->waitForTimer();
    doWork();
}

CreateTimerThread() should return the thread object you want, and run would be something like:

run()
{
    while( false == shutdownLatch() )
    {
        Sleep( timeout );
        pulseTimerEvent();
    }
}

waitForTimer()
{
    WaitForSingleObject( m_handle );
    return;
}
于 2012-05-18T13:44:02.167 回答