执行/停留在循环中一段确定的时间,例如1分钟

时间:2019-04-10 21:02:28

标签: c++

我想制作一个运行while循环一段定义时间的c ++程序,然后退出该循环。 让循环在运行时做一些事情,并且当达到时间设置时,它将脱离循环。例如,当循环正在运行时,它将在屏幕上继续打印内容;经过1分钟后,它将退出循环。

#include <iostream>
#include <time.h>


using namespace std;

int main()
{

    time_t now = time(nullptr);
    tm* current_time = localtime(&now);

    int current_minute = current_time->tm_min;

    int defined_minute = current_minute + 1;

    while (current_minute < defined_minute)
    {
        current_minute = current_time->tm_min;
    }
}

我创建了这段代码,它本来可以正常运行,但是我尝试调试,但是我仍然不明白为什么它不起作用。

P.S。这是我第一次在网上发布编程问题,如果有人告诉我将来如何更好地解决我的问题,我们将不胜感激。

4 个答案:

答案 0 :(得分:1)

使用#include <chrono>

auto t0 = std::chrono::system_clock::now();
while ( (std::chrono::system_clock::now()-t0) < std::chrono::minutes{1})
{
    // do stuff
}

答案 1 :(得分:1)

这是最简单的答案:

#include <chrono>
#include <iostream>

int
main()
{
    using namespace std;
    using namespace std::chrono;
    auto finish = system_clock::now() + 1min;
    do
    {
        cout << "stuff\n";
    } while (system_clock::now() < finish);
}

这需要C ++ 14或C ++ 17。如果您使用的是C ++ 11,请用minutes{1}代替1min。如果您使用的是C ++ 03,则<chrono>不可用,您将不得不使用C API进行计时,这显然很难使用。

Here is a video tutorial on <chrono>.

答案 2 :(得分:0)

此代码段至少需要C ++ 11,并且可能包含一些复杂的C ++对象,但这是我的构想

#include <iostream>
#include <future>     //std::async
#include <atomic>
#include <chrono>
#include <sstream>

int main()
{   
    int i = 0;
    std::stringstream sstr;
    std::atomic<bool> do_it(true);

    //store future so that async returns immediately
    //see Notes paragraph on https://en.cppreference.com/w/cpp/thread/async
    auto fut = std::async(std::launch::async, [&do_it]() {
                                                        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
                                                        do_it = false;
                                                    });

    //Preemtion could steal some time here...

    while ( do_it )
    {
        sstr << "Iteration: " << ++i << "\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }

    std::cout << sstr.str() << "\n" << std::flush;

    std::cout << "Bye\n" << std::flush;
}

结果是(您可以在coliru之类的在线C ++编译器上进行尝试)

Iteration: 1
...
Iteration: 95
Iteration: 96
Iteration: 97
Iteration: 98

Bye

希望有帮助

答案 3 :(得分:0)

另一个答案可能是使用条件变量,以应对丑陋的 sleep_for(...),因为在我的第一个答案中经常使用它,导致98次迭代而不是100次迭代,因为应用程序/计算所花费的时间(此处在stringstream中打印一些循环号)。

条件变量可以针对多个线程

#include <iostream>
#include <thread>
#include <condition_variable>
#include <atomic>
#include <chrono>
#include <sstream>

//From https://en.cppreference.com/w/cpp/thread/condition_variable/wait_until

int index[2] = { 0 };
std::stringstream sstr;
std::condition_variable cv;
std::mutex cv_m;
std::atomic<bool> do_it(true);

std::mutex mut_print;

void foo(char id, int * index)
{ 
    if ( ! index ) return;

    auto new_tp = std::chrono::system_clock::now();

    while ( do_it )
    {   
        {
            std::lock_guard<std::mutex> lock(mut_print);
            sstr << "Iteration of "<< id << ": " << ++(*index) << "\n";
        }

        new_tp += std::chrono::milliseconds(10);

        while ( do_it )
        {   
            std::unique_lock<std::mutex> lk(cv_m);
            if(std::cv_status::timeout == cv.wait_until(lk,new_tp ) ) {
                break;
            }
        }
    }
}

void signals()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    do_it = false;
    cv.notify_all();
}

int main()
{   
    std::thread t1(foo,'A',&index[0]),t2(foo,'B',&index[1]),ts(signals);

    t1.join();
    t2.join();
    ts.join();

    std::cout << sstr.str() << "\n" << std::flush;

    std::cout << "Bye\n" << std::flush;
}

coliru

结果是

Iteration of A: 1
Iteration of B: 1
Iteration of A: 2
Iteration of B: 2
...
Iteration of A: 100
Iteration of B: 100
Iteration of A: 101
Iteration of B: 101

Bye

这一次我们进行了101次迭代,但此示例并没有假装执行有限/给定的次数