C++ 每 10 秒循环一次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10807681/
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 14:29:05  来源:igfitidea点击:

Loop every 10 second

c++

提问by user1417815

How to load a loop every 10 second and add +1 to the count and print it?

如何每 10 秒加载一个循环并将 +1 添加到计数中并打印它?

like:

喜欢:

int count;
    while(true)
    {
       count +=1;
       cout << count << endl; // print every 10 second 
    }

print:

打印:

1
2
3
4
5
ect...

i dont know how, please help me out guys

我不知道如何,请帮助我

回答by Viktor Latypov

My try. (Almost) perfectly POSIX. Works on both POSIX and MSVC/Win32 also.

我的尝试。(几乎)完美的 POSIX。也适用于 POSIX 和 MSVC/Win32。

#include <stdio.h>
#include <time.h>

const int NUM_SECONDS = 10;

int main()
{
    int count = 1;

    double time_counter = 0;

    clock_t this_time = clock();
    clock_t last_time = this_time;

    printf("Gran = %ld\n", NUM_SECONDS * CLOCKS_PER_SEC);

    while(true)
    {
        this_time = clock();

        time_counter += (double)(this_time - last_time);

        last_time = this_time;

        if(time_counter > (double)(NUM_SECONDS * CLOCKS_PER_SEC))
        {
            time_counter -= (double)(NUM_SECONDS * CLOCKS_PER_SEC);
            printf("%d\n", count);
            count++;
        }

        printf("DebugTime = %f\n", time_counter);
    }

    return 0;
}

This way you can also have the control on each iteration, unlike the sleep()-based approach.

通过这种方式,您还可以控制每次迭代,这与基于 sleep() 的方法不同。

This solution (or the same based on high-precision timer) also ensures that there is no error accumulation in timing.

这种方案(或同样基于高精度定时器的方案)也保证了时序上没有误差累积。

EDIT: OSX stuff, if all else fails

编辑:OSX 的东西,如果一切都失败了

#include <unistd.h>
#include <stdio.h>

const int NUM_SECONDS = 10;

int main()
{
    int i;
    int count = 1;
    for(;;)
    {
        // delay for 10 seconds
        for(i = 0 ; i < NUM_SECONDS ; i++) { usleep(1000 * 1000); }
        // print
        printf("%d\n", count++);
    }
    return 0;
}

回答by Nemanja Boric

On Windows, you can use Sleepfrom windows.h:

在 Windows 上,您可以使用Sleepfrom windows.h

#include <iostream>
#include <windows.h>


int _tmain(int argc, _TCHAR* argv[])
{
    int count = 0;
    while(true)
    {
        count +=1;
        std::cout << count  << std::endl;
        Sleep(10000);
    }
}

回答by stan

Use sleep(): http://www.gnu.org/software/libc/manual/html_node/Sleeping.html

使用sleep()http: //www.gnu.org/software/libc/manual/html_node/Sleeping.html

int count = 0;
while(true)
{
    count++;

    cout << count << endl; // print every 10 second 
    sleep(10);

}

回答by SirPentor

As others have said, you want a sleep() function. Cross-platform issues can come up though. I found this threadabout that issue, which you may want to look at.

正如其他人所说,您需要一个 sleep() 函数。但是可能会出现跨平台问题。我找到了关于这个问题的帖子,你可能想看看。

回答by gahcep

Here is yet another example using Windows Waitable Timer. Short quote from MSDN page:

这是另一个使用 Windows Waitable Timer 的示例。来自 MSDN 页面的简短引用:

A waitable timerobject is a synchronization object whose state is set to signaled when the specified due time arrives. There are two types of waitable timers that can be created: manual-reset and synchronization. A timer of either type can also be a periodic timer.

等待计时器对象是一个同步对象,其状态设置为在指定的到期时间到达时发出信号。可以创建两种类型的可等待计时器:手动重置和同步。任一类型的计时器也可以是周期性计时器

Example:

例子:

#include <Windows.h>
#include <iostream>

void main(int argc, char** argv)
{
    HANDLE hTimer = NULL;
    LARGE_INTEGER liTimeout;

    // Set timeout to 10 seconds
    liTimeout.QuadPart = -100000000LL;

    // Creating a Waitable Timer
    hTimer = CreateWaitableTimer(NULL, 
                                 TRUE,              // Manual-reset
                                 "Ten-Sec Timer"    // Timer's name
                                );
    if (NULL == hTimer)
    {
        std::cout << "CreateWaitableTimer failed: " << GetLastError() << std::endl;
        return;
    }

    // Initial setting a timer
    if (!SetWaitableTimer(hTimer, &liTimeout, 0, NULL, NULL, 0))
    {
        std::cout << "SetWaitableTimer failed: " << GetLastError() << std::endl;
        return;
    }

    std::cout << "Starting 10 seconds loop" << std::endl;

    INT16 count = 0;
    while (count < SHRT_MAX)
    {
        // Wait for a timer
        if (WaitForSingleObject(hTimer, INFINITE) != WAIT_OBJECT_0)
        {
            std::cout << "WaitForSingleObject failed: " << GetLastError() << std::endl;
            return;
        }
        else 
        {
            // Here your code goes
            std::cout << count++ << std::endl;
        }

        // Set a timer again
        if (!SetWaitableTimer(hTimer, &liTimeout, 0, NULL, NULL, 0))
        {
            std::cout << "SetWaitableTimer failed: " << GetLastError() << std::endl;
            return;
        }
    }
}

Also, you can use a Waitable Timerwith an Asynchronous Procedure Call. See thisexample on MSDN.

此外,您还可以将Waitable TimerAsynchronous Procedure Call 一起使用。请参阅MSDN 上的示例。